daniel.sedlacek
daniel.sedlacek

Reputation: 8629

Confusing TypeScript definition

I found this in a definition file and I am bit perplexed, how exactly is this supposed to be used?

interface Curve {
    [index: number]: Point;
}

where Point is

interface Point {
    x: number;
    y: number;
}

So the Curve is a class, right? But what is the array of Points, a method? how do I use it? What is the index in the array?

It is may not be relevant but the Curve is meant to be passed to a Bezier library like this:

interface JSBezier {
    distanceFromCurve(curve: Curve, point: Point): number;
    ...
}

Upvotes: 0

Views: 89

Answers (2)

WiredPrairie
WiredPrairie

Reputation: 59763

Even though there is only an interface such as Point, the TypeScript compiler will confirm that an object has a compatible signature at compile time.

So, when you see:

interface Curve {
    [index: number]: Point;
}

This means that there is an indexable property that accepts numbers and that the right hand side will always conform to the Point interface. Index signatures are defined in 3.7.4 of the TypeScript language specification.

It does not mean that an object won't also support indexed properties of type string, but that when they are numbers, they will be compatible with the Point interface.

Also, it means that if you have a class instance (Curve can be instantiated because it only has an index signature and no other properties/methods that it also must implement):

var c : Curve = {};

You can set new Points as long as they match the interface:

c[1] = { x: 1, y: 100 };

In the above, the index 1 has been assigned to a new object that matches the Point interface (as it has an x and a y property both of type numbers). You can also do:

c[2] = { x: 1, y: 100, z: -10 };

While there is another property, z, the object instance is still a Point by having x and y.

Upvotes: 2

basarat
basarat

Reputation: 275917

These are known as index signatures.

This one

interface Curve {
    [index: number]: Point;
}

means that if you index a curve by a number you get a point. i.e.

var foo:Curve;
var bar = foo [0]; // bar is inferred to be a Point

Upvotes: 3

Related Questions