在 Typescript 中使用 Symbol 键入通用类型?
Keying a generic type using a Symbol in Typescript?
我正在尝试做这样的事情:
function attachUUID<T>(o:T) {
o[Symbol('id')]=v1();
}
T
泛型类型是 class 定义或某个定义的 Typescript type
。 VSCode 错误是:
[ts] Element implicitly has an 'any' type because type '{}' has no index signature
您的代码不保证您正在使用的名为 属性 的符号已在 T
上声明。您可以将 T
约束为声明 属性:
的类型
const symbolId = Symbol('id');
function attachUUID<T extends { [symbolId]: string }>(o: T) {
o[symbolId]=v1();
}
否则转换为 any
:
function attachUUID<T>(o: T) {
(<any>o)[symbolId]=v1();
}
... 或者如果您想将符号分配给任何对象:
const idSym = Symbol('id');
function attachUUID<T>(o:T) {
type withUUID = T & { [idSym]: string };
(o as withUUID)[idSym] = v1();
return o as withUUID;
}
这样你之后就可以获得类型安全:
const el = attachUUID({ a: 1 });
console.log(el.a, el[idSym]);
我正在尝试做这样的事情:
function attachUUID<T>(o:T) {
o[Symbol('id')]=v1();
}
T
泛型类型是 class 定义或某个定义的 Typescript type
。 VSCode 错误是:
[ts] Element implicitly has an 'any' type because type '{}' has no index signature
您的代码不保证您正在使用的名为 属性 的符号已在 T
上声明。您可以将 T
约束为声明 属性:
const symbolId = Symbol('id');
function attachUUID<T extends { [symbolId]: string }>(o: T) {
o[symbolId]=v1();
}
否则转换为 any
:
function attachUUID<T>(o: T) {
(<any>o)[symbolId]=v1();
}
... 或者如果您想将符号分配给任何对象:
const idSym = Symbol('id');
function attachUUID<T>(o:T) {
type withUUID = T & { [idSym]: string };
(o as withUUID)[idSym] = v1();
return o as withUUID;
}
这样你之后就可以获得类型安全:
const el = attachUUID({ a: 1 });
console.log(el.a, el[idSym]);