Kohei Mikami
Kohei Mikami

Reputation: 2870

How to force key types in TypeScript interface?

I want to make an object interface which force to use string as keys, but TypeScript compiler pass codes even if it had a number type as a key. Why?

For example,

interface PriceI {
    [key:string]:number;
}

var coursePrice: PriceI = {};
coursePrice["Orange"] = 100;
coursePrice["Apple"] = 200;
coursePrice[3]=200;    // It should be compile error, but it pass
coursePrice[true]=300; // It's compile error

Upvotes: 0

Views: 1788

Answers (1)

Paleo
Paleo

Reputation: 23692

See the handbook:

There are two types of supported index signatures: string and number. It is possible to support both types of indexers, but the type returned from a numeric indexer must be a subtype of the type returned from the string indexer. This is because when indexing with a number, JavaScript will actually convert that to a string before indexing into an object. That means that indexing with 100 (a number) is the same thing as indexing with "100" (a string), so the two need to be consistent.

In your example, TypeScript considers that coursePrice[3] = 200; is equivalent to coursePrice["3"] = 200;.

Upvotes: 2

Related Questions