2

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.

2
  • 5
    And your name is undefined, that all makes sense now. :D Commented Sep 13, 2021 at 13:53
  • 1
    @RyanLe interface undefined extends Human Commented Sep 13, 2021 at 14:13

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the answer. Can you please explain why it works?
you just had them backwards, it's undefined extends a instead of a extends undefined
@undefined sure, give me a minute

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.