EN
TypeScript - declare variable type using nullable literal
9 points
In this short article, we would like to show how to declare nullable literal value and assign it to variable in Typescript.
Quick solution:
There is not available syntax that lets to create nullable literal, but there is some trick, what was show below:
xxxxxxxxxx
1
const nullable = <T extends unknown> (value: T): T | null => value;
2
3
4
// Usage example:
5
6
let a = nullable(true); // `a` variable has `boolean | null` type
7
let b = nullable(12345); // `b` variable has `number | null` type
8
let c = nullable('Some text here ...'); // `c` variable has `string | null` type