Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript array with minimum length

Tags:

typescript

How can you create a type in TypeScript that only accepts arrays with two or more elements?

needsTwoOrMore(["onlyOne"]) // should have error needsTwoOrMore(["one", "two"]) // should be allowed needsTwoOrMore(["one", "two", "three"]) // should also be allowed 
like image 642
KPD Avatar asked Apr 19 '18 00:04

KPD


People also ask

How do I limit array length in TypeScript?

position: Array<number>; ...it will let you make an array with arbitrary length. However, if you want an array containing numbers with a specific length i.e. 3 for x,y,z components can you make a type with for a fixed length array, something like this? Any help or clarification appreciated!

How do I create an array of specific size in TypeScript?

Use a tuple to declare an array with fixed length in TypeScript, e.g. const arr: [string, number] = ['a', 1] . Tuple types allow us to express an array with a fixed number of elements whose types are known, but can be different.

How do I find the length of a list in TypeScript?

var len= arr. length; //Now arr. length returns 5.


2 Answers

This can be accomplished with a type like:

type ArrayTwoOrMore<T> = {     0: T     1: T } & Array<T>  declare function needsTwoOrMore(arg: ArrayTwoOrMore<string>): void  needsTwoOrMore(["onlyOne"]) // has error needsTwoOrMore(["one", "two"]) // allowed needsTwoOrMore(["one", "two", "three"]) // also allowed 

TypeScript Playground Link

like image 64
KPD Avatar answered Sep 18 '22 14:09

KPD


This is an old question and the answer is fine (it helped me as well), but I just stumbled across this solution as well while playing.

I had already defined a typed Tuple (type Tuple<T> = [T, T];), and then below that, I had defined array of two or more as described above (type ArrayOfTwoOrMore<T> = { 0: T, 1: T } & T[];).

It occurred to me to try using the Tuple<T> structure in place of { 0: T, 1: T }, like so:

type ArrayOfTwoOrMore<T> = [T, T, ...T[]];

And it worked. Nice! It's a little more concise and perhaps able to be clearer in some use-cases.

Worth noting is that a tuple doesn't have to be two items of the same type. Something like ['hello', 2] is a valid tuple. In my little code snippet, it just happens to be a suitable name and it needs to contain two elements of the same type.

like image 33
Steve Adams Avatar answered Sep 16 '22 14:09

Steve Adams