shaunc
shaunc

Reputation: 5611

How do I create an interface that takes a symbol index in typescript?

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

Answers (3)

Benjamin Riggs
Benjamin Riggs

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

Michael Anderson
Michael Anderson

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

Related Questions