1

case 1

 type ArrayEqualLength<T,?> = [T]
 const a: ArrayEqualLength<number,1> = [1,1] // x
 const a: ArrayEqualLength<number,1> = [1] // o
 const a: ArrayEqualLength<number,2> = [1,1] // o

case 2 GreaterThan

 type ArrayGreaterThanLength<T,?> = [T]
 const a: ArrayGreaterThanLength<number,2> = [1,1] // x
 const a: ArrayGreaterThanLength<number,2> = [1] // x
 const a: ArrayGreaterThanLength<number,2> = [1,1,1] // o

I want to check array length in typescript!

I can't find it when I search. Help me. Thanks.

bugtype kr
  • 365
  • 1
  • 4
  • 8

1 Answers1

2

This might help with your first case: https://stackoverflow.com/a/52490977/12414867

For example:

type TupleEq<TItem, TLength extends number> = [TItem, ...TItem[]] & { length: TLength };
const a: TupleEq<number, 4> = [1, 2, 3, 4];

As for the second case, I'm not sure if it's possible in TS :/

msarakon
  • 240
  • 1
  • 6