0

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
1
  • 1
    The static typing in typescript is a compromise between the highly dynamic nature of javascript and the rigid type-enforcement in most strongly typed languages. I myself would prefer a stricter TS, but the designers are afraid to scare away people coming from JS. Commented May 6, 2016 at 11:07

1 Answer 1

2

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;.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.