Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript: interface for fixed size array

Tags:

typescript

Is there a way in typescript define fixed size array. say, for example, in a function definition, I need to able to say

coord: (c:any) => number[]; //how to say it is an array of size 4

can I define an interface like we define a hash map

//this doesn't work
interface IArray{
  [number]
}

and also restrict max length to be 4.

like image 833
bsr Avatar asked Mar 28 '14 18:03

bsr


People also ask

How do I create a fixed size array 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 you write an interface for an array of objects?

To define an interface for an array of objects, define the interface for the type of each object and set the type of the array to be Type[] , e.g. const arr: Employee[] = [] . All of the objects you add to the array have to conform to the type, otherwise the type checker errors out.

How do you define an array in TypeScript interface?

One of which is Array of Objects, in TypeScript, the user can define an array of objects by placing brackets after the interface. It can be named interface or an inline interface.

Can TypeScript interface have methods?

A TypeScript Interface can include method declarations using arrow functions or normal functions, it can also include properties and return types. The methods can have parameters or remain parameterless.


1 Answers

You could return a tuple instead of an array:

type array_of_4 = [number, number, number, number];

var myFixedLengthArray :array_of_4 = [1,2,3,4];

// the tuple can be used as an array:
console.log(myFixedLengthArray.join(','));
like image 148
R D Avatar answered Sep 20 '22 13:09

R D