5

I want to check if a type is nullable or not, and if it has a conditional type on the value.

I tried implementing

type IsNullable<T> = T extends null ? true : false;

However, it does not seem to work

type test = IsNullable<number> // Returns false as it should
type test = IsNullable<number | null> // Returns false when it should be true

What's the proper way of checking if a type is nullable? I tried with T extends null | T and did not work either.

1

1 Answer 1

11

You can switch the left and right side of the extends, so

type IsNullable<T> = null extends T ? true : false;

should work for you.

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

3 Comments

No, it does not work as IsNullable<number> returns true. However if I change from IsBoolean<T> = boolean extends T ? true : false then it works. It seems everything extends null?
@Marc, it does work. Make sure strictNullChecks enabled. Playground
Yes, @AlekseyL. has a good point there. If you do not enable strictNullChecks in your tsconfig.json, every type extends null. You should really set strict: null there.

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.