typescripttypescript2.0

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?


Solution

  • 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.