0

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.

2
  • 3
    Did you try { [_ 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. Commented Apr 12, 2022 at 15:21
  • 1
    You could also write { [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. Commented Apr 12, 2022 at 16:22

1 Answer 1

2

You can use an intersection of mapped types:

public get value(): { [_ in K0]: V0 } & { [_ in K1]: V1 } {
    // returning value...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.