bsr bsr - 15 days ago 14
TypeScript Question

typescript: interface for fixed size array

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.

Answer

It's sort of awkward, but you can do it like this:

interface SizeFour<T> {
    0: T;
    1: T;
    2: T;
    3: T;
}

function fn(): SizeFour<string> {
    // Need to cast
    return <any>['', '', '', ''];   
}

var x = fn();
var a = x[0]; // a: string
var b = x[4]; // b: any; error if --noImplicitAny