bsr bsr - 1 year ago 330
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{

and also restrict max length to be 4.

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download