在TypeScript中使用多个泛型参数作为对象键



有没有办法在TypeScript中使用多个泛型参数作为对象键
当只有一个参数时,我在这里找到的答案很好,但当有更多参数时就不行了。错误";映射类型不能声明属性或方法";如果我尝试声明多个[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 <=> V0K1 <=> V1等之间的连接。

您可以使用映射类型的交集:

public get value(): { [_ in K0]: V0 } & { [_ in K1]: V1 } {
// returning value...
}

最新更新