assuming I have this type:
type FooArray = IFoo[] | number[] | undefined
is it possible to extract just IFoo
from this?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With