2

I'm trying to dynamically generate a type based on the key(s) of an existing type.

interface A {
    X: number
}

type S = keyof A // correct "X"
type V = A[S] // correct: number

type B = {
    [S]: A[S] // Error: A computed property name in a type literal must refer to an
              // expression whose type is a literal type or a 'unique symbol' type.

}

What is the correct way to generate a type with dynamic properties based on the key of another type?

3
  • You're trying to create interface B which will be exactly the same as A? What is the point of that? Commented May 19, 2022 at 19:46
  • 2
    @JuanMendes my actual use case is a bit more complicated... it ended up like {[K in keyof T]: {get(this: {[S in typeof key]: number}): T[K]}} I just tried to simplify to the part I was having trouble with so the question was concise and answerable. Commented May 19, 2022 at 20:18
  • Now I want to know what that is doing 😜 Looks gnarly! Commented May 19, 2022 at 20:32

1 Answer 1

2

You were really close. All you need to change is [S]: A[S] to [k in S]: A[k].

interface A {
    X: number
    Y: string;
}

type S = keyof A;

type B = {
    [k in S]: A[k];
}

playground

Sign up to request clarification or add additional context in comments.

5 Comments

Documentation for Mapped Types in Typescript has almost this exact same code for a Partial implementation. I'm really curious as to how the OP wants to use it since this doesn't really achieve anything, just a copy of the original type?
@JuanMendes I assume this is part of a larger type. Maybe B consists of props from many other interfaces, and has props of its own. While there are more elegant ways of constructing such a type, it may not be obvious to new typescript users.
What you just described is just extends, isn't it? 😅
@JuanMendes yupp :P
Thanks I ran into some confusion about the interactions between keyof, typeof and in and this helped me out!

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.