有沒有辦法在 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...
}
}
基本上我希望能夠根據建構式中給出的泛型型別回傳一個型別化的值。
我可以使用 a [key in ClassWithAllKeys],但我想我會失去 , 等之間的K0 <=> V0聯系K1 <=> V1。
uj5u.com熱心網友回復:
您可以使用映射型別的交集:
public get value(): { [_ in K0]: V0 } & { [_ in K1]: V1 } {
// returning value...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/460192.html
