Is there any way to check if a type includes 'undefined' type?
type a = boolean | undefined;
type v = a extends undefined ? 'yes' : 'no'
I tried with extends, but it doesn't work.
Try to use conditional type with extra generic parameter
type a = boolean | undefined;
type IsUndefined<T> = undefined extends T ? true : false
type Result = IsUndefined<a> // true
type Result2 = IsUndefined<number | string> // false
When conditional types act on a generic type, they become distributive when given a union type (distributive-conditional-types). For example, take the following.
If we plug a union type into IsUndefined, then the conditional type will be applied to each member of that union.
type IsUndefined<T> = T extends undefined ? true : false
type Result = IsUndefined<string> | IsUndefined<undefined> // boolean
IsUndefined<string> returns false
IsUndefined<undefined> returns true
Hence, Result is boolean because a union of true and false is a boolean.
But, if you put undefined before extends then conditional type will be applied to the whole union
undefined extends a instead of a extends undefined
undefined, that all makes sense now. :Dinterface undefined extends Human