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

2

9

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.

Aynat answered 21/11, 2018 at 2:59 Comment(5)
[key: string]?Raymond
I tried this [key: string | symbol] didn't work eitherAynat
Unfortunately this issue appears to still be outstanding (I was actually led here by your comment on GitHub). I've just pinged some TS maintainers to see if there's anything that can be done.Pteridology
Does anybody have an update on this ?Cardoso
github.com/microsoft/TypeScript/issues/1863 @CardosoQuintet
S
2

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!"
Syriac answered 10/11, 2023 at 1:9 Comment(0)
C
-1

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';
Cart answered 29/1, 2021 at 9:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.