我有这个:
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;
};
我收到此错误:
TS2538:类型“唯一符号”不能用作索引类型。
有人知道这个错误是什么意思吗?我使用的是 tsc 版本3.1.6。
这有效:
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!"
我糟糕的解决方法:
const bar: Record<any, string> = {};
const FOO = Symbol('foo');
// eslint-disable-next-line @typescript-eslint/no-explicit-any
bar[FOO as any] = 'sad';