Reputation: 5611
I want to create an interface for an object that returns subobjects with string indices, and a string name with a symbol interface. I tried the following:
const $name = Symbol.for('name')
interface Foo {
[key: string] : Foo
[name: $name] : string
}
However, I get the error: An index signature must be a string or a number
. But ... its not true that indexes must be strings or numbers, at least for modern javascript versions? How can I declare my object or work around this problem?
Upvotes: 5
Views: 4336
Reputation: 761
This is now fixed in Typescript (4.9):
https://github.com/microsoft/TypeScript/pull/44512
https://devblogs.microsoft.com/typescript/announcing-typescript-4-9/
Upvotes: 2
Reputation: 678
A temporary workaround, if you have a small number of symbols you want to use, is to add them to the SymbolConstructor
interface in your globals.d.ts
file, and then set them in your code:
// globals.d.ts
interface SymbolConstructor {
$name: symbol;
}
// code.ts
const $name = Symbol.for('name');
Symbol.$name = $name;
interface Foo {
[key: string] : Foo
[Symbol.$name] : string
}
Upvotes: 1
Reputation: 73580
It seems that at the moment you can not do this for custom symbols (unless I'm misreading the thread). This is a known issue and is being tracked as https://github.com/Microsoft/TypeScript/issues/1863
Upvotes: 3