Exploring the Record
type led me to an unexpected discovery while working in Typescript 5.16.
If I define a Record<string, T>
type and create this object:
const a: Record<string, T> = {
123: someData,
x: someData
}
This code runs without errors. The reason for this is likely because in JavaScript, number indices on objects are automatically converted to strings, so this behavior is somewhat anticipated.
However, if I introduce a symbol
type as a key, it does not produce any errors (symbols typically do not get coerced into other types). Even with a Record<number, T>
, symbols can be used as keys alongside numeric indices.
What adds to the confusion is that if I try something like
const a: Record<number, T> = {
123: someData,
[Symbol.for("ABCD")]: someData
}
the compilation is successful. However, using a predefined symbol like Symbol.iterator
(only when the key type is number
as in the previous example) results in an expected error. View here.
Is there a specific reason for this unusual behavior or have I overlooked something?