Conditional types for nullable in Typescript

Mar*_*arc 1 types nullable conditional-statements typescript

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;
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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

phr*_*hry 6

您可以切换 的左侧和右侧extends,因此

type IsNullable<T> = null extends T ? true : false;
Run Code Online (Sandbox Code Playgroud)

应该为你工作。

  • @Marc,它确实有效。确保启用“strictNullChecks”。[游乐场](https://www.typescriptlang.org/play/index.html#code/C4TwDgpgBAkgzgOQK4BsUEMBGKIB4AqAfFALxQB2qKUEAHsBOQCZxT5QD8UwATktAC4oAM3Qo4EANwAoAPSzu4aAzjBSsRFSw5clALaYIPQtNCRuEVevjI02vPsM8oA HwpVCkoA) (3认同)