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?
CodePudding user response:
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];
}