I am attempting to create an object with a symbol as the key type, following MDN's guidance:
A symbol value may be used as an identifier for object properties [...]
However, when trying to use it as the key property type:
type obj = {
[key: symbol | string]: string
}
I encounter the following error:
TS1023: An index signature parameter type must be either 'string' or 'number'.
even though it is possible to use it as an index type. I am working with the latest version of TypeScript (v3.7.2), and I have come across related questions:
- Typescript: destructuring an object with symbols as keys (He's using an actual instance of a Symbol, I want the type
symbol
) - TypeScript: An index signature parameter must be a 'string' or 'number' when trying to use string | number
- ES6: destructuring an object with symbols as keys (That can't be a solution - it seems kinda wrong to use an actual instance as type since every Symbol instance is unique...)
I have also consulted the typescript symbol docs, but they only demonstrate how it is used as a value, not as a type.
Example:
const obj = {} as {
[key: number | symbol]: string // Won't work
};
const sym = Symbol('My symbol');
obj[sym] = 'Hi';