Reputation: 10823
Say I have the following code:
function myFunction(x: { foo: number } | { bar: string }) {
How can I write some code to determine whether x
is the first or second type?
Things I've considered:
x is MyType
function to check for a foo
property. Yes, I could do this, but it seems overkill for types that are only used as arguments to a single function. if ((x as { foo: number}).foo) { let y = x as { foo: number }
. I could do this, but it defeats the point of a type system.type
property. Again, seems like overkill for types that are only used as arguments for one function.Upvotes: 2
Views: 816
Reputation: 159855
It is also a work-around, but you can unify the fields of the types by extending your existing types with optional fields typed to never
so that each type theoretically has every field possible in the union:
{ foo: number, bar?: never } | { bar: string, foo?: never }
By making the superset type contain all the fields you can run type checks like:
type CompletelyDisjointed = { foo: number, bar?:never } | { foo?: never, bar: string };
function myFunction(x: CompletelyDisjointed): string | number {
if (typeof x.bar === 'string') {
return x.bar;
} else {
return x.foo;
}
}
Upvotes: 4