Unfortunately this is not possible at the moment in TypeScript.(不幸的是,目前在TypeScript中这是不可能的。)
If you have to interoperate with some APIs that expect this or really want to use symbols as keys, you can do this awkward version:(如果您必须与某些期望使用此API的API进行互操作,或者真的要使用符号作为键,则可以使用以下笨拙的版本:)
// Ensure we can not pass regular map to our custom functions
type SymbolMapTag = { readonly symbol: unique symbol }
type SymbolMap = SymbolMapTag & {
[Key in string | number | symbol]: string;
}
function set_symbol<T extends SymbolMap, TSym extends symbol>
(target: T, sym: TSym, value: T[TSym]) {
target[sym] = value;
}
function get_symbol<T extends SymbolMap, TSym extends symbol>
(target: T, sym: TSym): T[TSym] {
return target[sym];
}
const symbol_map = {} as SymbolMap;
const sym = Symbol('My symbol');
set_symbol(symbol_map, sym, "hi");
get_symbol(symbol_map, sym); // string
type NonSymbolMap = {
[Key in string | number]: string;
}
const non_symbol_map = {} as NonSymbolMap;
set_symbol(non_symbol_map, sym, "hi"); // error
get_symbol(non_symbol_map, sym); // error
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…