Using symbol as object-key type in TypeScript

TypeScript 4.4 allows symbols in index signatures:

type SymbolIndex = {
    [key: symbol | string]: string // works
}

const sym = Symbol("descr");
const t1: SymbolIndex = {
    "foo": "bar",
    [Symbol.iterator]: "qux",
    sym: "sym"
};

// all result in string
t1.foo 
t1.sym 
t1[Symbol.iterator]
t1["oh"]

Playground

With older versions, SymbolIndex will trigger an error:

An index signature parameter type must be either ‘string’ or ‘number’.(1023)

Alternative

If you just want an object type with symbols and no index signature, you can already do that today:

const sym = Symbol() // note const (no let) 
type O = {
    foo: string
    [Symbol.iterator]: string
    [sym]: number
}

let o: O = { [sym] : 3, [Symbol.iterator]: "bar", foo: "qux"}

let { [sym]: symVal } = o

Playground

Leave a Comment