有没有一种方法可以在中使用多个泛型参数作为对象键?
当只有一个参数时,The answer I found here工作得很好,但当有更多参数时,就不能工作了。如果我尝试声明多个[key in T]
,“映射类型可能不会声明属性或方法”。
例如,我有一门课:
export class DynamicForm<
K0 extends string, V0,
K1 extends string, V1,
...
> {
public get value(): {
[key in K0]: V0;
[key in K1]: V1; // ERROR: A mapped type may not declare properties or methods. ts(7061)
...
} {
// returning value...
}
public constructor(
input0?: InputBase<K0, V0>,
input1?: InputBase<K1, V1>,
...
) {
// doing stuff...
}
}
基本上,我希望能够根据构造函数中给定的泛型类型返回一个类型化的值。
我可以使用[key in ClassWithAllKeys]
,但我想我会失去K0 <=> V0
、K1 <=> V1
等之间的连接。
发布于 2022-04-12 18:14:20
您可以使用映射类型的交集:
public get value(): { [_ in K0]: V0 } & { [_ in K1]: V1 } {
// returning value...
}
https://stackoverflow.com/questions/71845152
复制相似问题