Home > Software design >  Use multiple generic parameters as object keys in TypeScript
Use multiple generic parameters as object keys in TypeScript

Time:04-13

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.

CodePudding user response:

You can use an intersection of mapped types:

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