Conditional Types
Conditional types were introduced in TypeScript 2.8 and allow complex type expressions, some of which drive some of the built-in types we saw earlier. These are really powerful, since they allow us to write logic inside our types. The syntax for this is T extends U ? X : Y
. This is very similar to the regular JavaScript ternary operator, which allows for inline conditions, the only difference in the syntax is that you have to use the extends
keyword and that this check is done at compile time and not runtime.
This allows us to write a NonNullable<T>
type:
type NonNullable<T> = T extends null | undefined ? never : T;
This is already built into the language, but it's driven by the same code you could write in your app.
This means that you can check whether a type is nullable at compile time and change the type signature or inference based on that. An example use case for this would be an isNonNullable
function. Consider the following code...