Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract single Type from a union?

assuming I have this type:

type FooArray = IFoo[] | number[] | undefined

is it possible to extract just IFoo from this?

like image 360
lonewarrior556 Avatar asked Jan 28 '23 10:01

lonewarrior556


2 Answers

Yes. Since TypeScript 2.8 supports conditional types you can do:

interface IFoo { 
    name: string
}

type FooArray = IFoo[] | number[] | undefined

type FindType<TWhere> = TWhere extends (infer U)[] ? (U extends object ? U : never) : never

type FoundType = FindType<FooArray> // FoundType == IFoo

Note that the U extends object ? U : never is required so that number is not matched.

like image 152
miensol Avatar answered Jan 31 '23 22:01

miensol


For Completeness Exclude along with a type query can also be used resulting in something pretty readable

interface IFoo { 
    name: string
}

type FooArray = IFoo[] | number[]  | undefined

type ArrayValues = Exclude<FooArray, undefined>[number] // IFoo | number

type IFooExtracted = Exclude<ArrayValues, number> // IFoo
like image 42
lonewarrior556 Avatar answered Jan 31 '23 22:01

lonewarrior556