One way to achieve this is by:
const supported = ["a", "b", "c"] as const;
const someObject: Record<typeof supported[number], number> = {a: 2, b: 3};
This ensures that all values are numbers and the object contains keys from supported
.
If needed, you can relax the value type to be unknown
or any
.
If you prefer not to use the built-in Record<K, V>
type, you can expand it to
{ [P in typeof supported[number]]: number }
.
Note: the values in supported
must be known during compile time.
Check out the Playground for more examples: Playground Link
Update:
A solution for making keys optional:
const supported = ["a", "b", "c", "d", "e"] as const;
type Keys = typeof supported[number];
type OptionalKeys = "d" | "e";
type MandatoryKeys = Exclude<Keys, OptionalKeys>
const someObject: Record<MandatoryKeys, number> & Partial<Record<OptionalKeys, number>> = {a: 2, b: 3, c: 42};
Explore more on the Playground: Playground Link