Is there a way to use multiple generic parameters as object keys in TypeScript?
The answer I found here works fine when there is only one parameter, but not when there is more. The error "A mapped type may not declare properties or methods" appears if I try to declare more than one [key in T].
A class I have for example:
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...
}
}
Basically I want to be able to return a typed value based on the generic types given in the constructor.
I could use a [key in ClassWithAllKeys], but then I think I would lose the connection between K0 <=> V0, K1 <=> V1, etc.
{ [_ in K0]: V0 } & { [_ in K1]: V1 } & ...? In my experience it worked fine, but it may be different for your use case. Please add a minimal reproducible example preferably as a TypeScript playground too.{ [P in K0 | K1]: P extends K0 ? V0 : P extends K1 ? V1 : never }. But the suggestion from @kellys is definitely the way to go as it is clearer and more conventional.