TS2538: Type 'unique symbol' cannot be used as an index type

6.8k Views Asked by At

I have this:

const symbols = {
   typeMap: Symbol('type.map')
}

interface LangMap {
  [key: string]: string | true,
  golang: string,
  typescript: string,
  java: string,
  swift: string
}

export const setTypeMap = function(v: LangMap) : LangMap{
  v[symbols.typeMap] = true;
  return v;
};

I get this error:

TS2538: Type 'unique symbol' cannot be used as an index type.

enter image description here

Does anyone know what that error is about? I am on tsc version 3.1.6.

2

There are 2 best solutions below

0
On

This works:

type SymbolObject<T extends object = Record<any,any>, K = T[keyof T]> = {
[key:string|number|symbol]:K
}
// it would be advised to have true type definitions here, but that's annoying.
const bar:SymbolObject = {};
const foo = Symbol("foo");
bar[foo] = "hello!"
0
On

My poor workaround :

const bar: Record<any, string> = {};
const FOO = Symbol('foo');

// eslint-disable-next-line @typescript-eslint/no-explicit-any
bar[FOO as any] = 'sad';