It appears that typescript permits the casting of any type to a map with keys of type number
. Consider this example code:
type NumberMap = {
[key: number]: string
}
type AnyType = {
foo: string
bar: boolean[]
}
const anyTypeObj: AnyType = { foo: "foo", bar: [false] }
const numberMap: NumberMap = anyTypeObj
I initially thought that the last line would result in a type error when trying to assign AnyType
to NumberMap
, but surprisingly it does not. However, directly assigning an object literal to a variable of type NumberMap
does lead to a type error:
const numberMap: NumberMap = { foo: "foo", bar: [false] }
View the link to see the above code on the typescript playground.
What leads typescript to allow the casting of objects of any type to NumberMap
?
Is there something distinctive about the type { [key: number]: string }
that causes this behavior?