Home > Software design >  Type definition for an object with generic keys
Type definition for an object with generic keys

Time:10-19

I would like to find a type definition for something as follows:

const x: Keys<"A"|"B"> = {
 "A": number, // type of value never changes and doesn't need to be generic
 "B": number
};

Ideally, objects of this Keys<T> type would require having a key for every type in T, and couldn't have a key that's not under T. The closest I've gotten is type Keys<T> = { [key in T]: number }, but then when used as follows:

const obj: Keys<"x"|"y"> = { "x": 1, "y": 2 };
obj["x"] // TS compiler fails with below message

Element implicitly has an 'any' type because expression of type '"x"' can't be used to index type '{ x: number; } | { y: number; }'. Property 'x' does not exist on type '{ a: number; } | { b: number; }'.ts(7053)

I've also tried several variants of passing the generic type parameter as an array, so like Keys<["key1", "key2"]>, to less success than what I have above.

CodePudding user response:

Something like this would do the trick, an object which receives the keys and has the value typed as numbers:

type Keys<K extends string> = Record<K, number>;

const obj: Keys<"x"|"y"> = { "x": 1, "y": 2 };

CodePudding user response:

I had simplified my question from the real example I'm working with, and this simplification turned out to be non-trivial.

type Keys<K extends string> = Record<K, number>; or type Keys<T> = { [key in T]: number } fit the criteria of this post.

  • Related