Last active
April 19, 2018 20:08
-
-
Save GingerBear/0e640bc5f722de2107ba00c8c680c729 to your computer and use it in GitHub Desktop.
union type check
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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