Home > Mobile >  What is the proper way to type for Array with a single NonNullable element?
What is the proper way to type for Array with a single NonNullable element?

Time:10-26

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:

You must have Example output from TypeScript playground

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
  • Related