I want the proper type for Array with a single NonNullable element
[] //error
[null] //error
[undefined] //error
[5] // good
[1, 2] // error
Any idea? Thanks!
CodePudding user response:
See example on TypeScript playground.
Update: if you want to use generics so that you can specify the type of the element in the array, you can just use type MyArray<T> = [T];
:
type MyArray<T> = [T];
const arr1: MyArray<number> = []; //error
const arr2: MyArray<number> = [null]; //error
const arr3: MyArray<number> = [undefined]; //error
const arr4: MyArray<number> = [1, 2]; // error
const arr5: MyArray<string> = [5]; // error
const arr6: MyArray<number> = [5]; // good
const arr7: MyArray<string> = ['lorem']; // good
const arr8: MyArray<boolean> = [true]; // good