在 TypeScript 中使用符号作为对象键类型 [英] Using symbol as object-key type in TypeScript
问题描述
我正在尝试使用 定义一个对象符号 作为键类型,因为 MDN 说:
I'm trying to define an object with a symbol as key-type since MDN says:
符号值可以用作对象属性的标识符[...]
A symbol value may be used as an identifier for object properties [...]
但是使用它作为键属性的类型:
But using it as type for the key-property:
type obj = {
[key: symbol | string]: string
}
导致以下错误:
TS1023:索引签名参数类型必须是字符串"或数字".
TS1023: An index signature parameter type must be either 'string' or 'number'.
即使它可以用作索引类型.我使用的是最新的打字稿版本 (v3.7.2
),我发现的相关问题:
even it can be used as index-type.
I'm using the latest typescript version (v3.7.2
), related questions I've found:
- 打字稿:以符号为键解构对象(他使用的是 Symbol 的实际实例,我想要 type
symbol
) - TypeScript:一个尝试使用字符串时,索引签名参数必须是字符串"或数字" |号码
- ES6:以符号为键解构对象(这不是一个解决方案 - 使用实际实例作为类型似乎有点错误,因为每个 Symbol 实例都是唯一的...)
- Typescript: destructuring an object with symbols as keys (He's using an actual instance of a Symbol, I want the type
symbol
) - TypeScript: An index signature parameter must be a 'string' or 'number' when trying to use string | number
- ES6: destructuring an object with symbols as keys (That can't be a solution - it seems kinda wrong to use an actual instance as type since every Symbol instance is unique...)
我还查看了 打字稿符号文档但它们只显示如何将其用作值,而不是用作类型.
I've also took a look at the typescript symbol docs but they only show how it's used as value, not as type.
示例:
const obj = {} as {
[key: number | symbol]: string // Won't work
};
const sym = Symbol('My symbol');
obj[sym] = 'Hi';
推荐答案
很遗憾,目前在 TypeScript 中无法实现.如果你必须与一些期望这个或真的使用符号作为键的 API 进行互操作,你可以做这个尴尬的版本:
Unfortunately this is not possible at the moment in 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:
// 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
这篇关于在 TypeScript 中使用符号作为对象键类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!