undefined
undefined

Reputation: 6844

Typescript check it type includes undefined

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.

Upvotes: 2

Views: 1201

Answers (1)

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

Playground

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

Upvotes: 3

Related Questions