I'm trying to define an object with a symbol as key-type since MDN says:
A symbol value may be used as an identifier for object properties [...]
But using it as type for the key-property:
type obj = {
[key: symbol | string]: string
}
results in the following error:
TS1023: An index signature parameter type must be either 'string' or 'number'.
even it can be used as index-type.
I'm using the latest typescript version (v3.7.2
), related questions I've found:
- 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've also took a look at the typescript symbol docs but they only show how it's used as value, not as type.
Example:
const obj = {} as {
[key: number | symbol]: string // Won't work
};
const sym = Symbol('My symbol');
obj[sym] = 'Hi';
symbol
? Maybe show an example of how you want to use yourtype obj
- I doubt that all symbol-keyed properties will bestring
s. – Bergiany
which is bad practice). – SimonMap<Symbol,String>
as we have Map , if that would serve the purpose of what you are trying to achieve – pavan kumar