2

According to Typescript documentation when using object literal it should exactly match interface. But for the following code playground does not show any error message:

code pic from playground

Here prop is string so it conflicts with [index: number]: number which means the index should be a number and value at that index should be a number, for properties other than name and age.

Is it a bug? If I am wrong please explain how this is working?

3
  • 3
    Do not post images of code. Commented Aug 22, 2016 at 13:03
  • I posted it to point out no error is being showed in playground. Commented Aug 22, 2016 at 13:11
  • It's very easy to generate a link for a playground example. This way, people trying to answer your question can quickly check the code out. Otherwise just pasting the code here, so a reviewer can try to compile it is always a better alternative then a picture. Commented Aug 22, 2016 at 17:38

2 Answers 2

1

You can always specify more properties than the interface requires. As demonstration, have a look at this code: (or on the playground)

// index.ts
interface MyInterface {
  obligatoryProperty: string
  optionalProperty?: string
  [index: number]: number  
}

let impl1: MyInterface = {} // fails compilation
let impl2: MyInterface = { obligatoryProperty: 'hello' } // compiles fine
let impl3: MyInterface = {
  obligatoryProperty: 'hello',
  optionalProperty: 'hello',
  2: 2,
  3: 3,
  notSpecifiedPropertyThatIsAlsoNotANumber: 'hello',
} // Still fine
Sign up to request clarification or add additional context in comments.

Comments

0

Because they decided to do "implicit index signatures", which is a good thing! You can read about the reasons here:

https://github.com/Microsoft/TypeScript/issues/7059

But the TypeScript compiler will show an error if you create a property that has a number as key and a non-number as value. Here is an example in the playground.

On a side note: TypeScript tries to be liberate where it can. You can omit parameters from a function signature. See this example.

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.