Reputation: 548
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:
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?
Upvotes: 2
Views: 495
Reputation: 16846
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.
Upvotes: 0
Reputation: 2579
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
Upvotes: 1