Skip to content

Instantly share code, notes, and snippets.

@GingerBear
Last active April 19, 2018 20:08
Show Gist options
  • Save GingerBear/0e640bc5f722de2107ba00c8c680c729 to your computer and use it in GitHub Desktop.
Save GingerBear/0e640bc5f722de2107ba00c8c680c729 to your computer and use it in GitHub Desktop.
union type check
type typeA = { a: string };
type typeB = { b: string };
type typeAorB = typeA | typeB;
// type check for union type
function isA(foo: typeA | typeB): foo is typeA {
return (<typeA>foo).a !== undefined;
}
// usage
const foo: typeAorB[] = [{ a: '123' }, { b: '234' }];
foo.forEach(f => {
if (isA(f)) {
console.log(f.a);
} else {
console.log(f.b);
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment