I need to create a set of server types in a union like this:
type Union = 'A' | 'B' | 'C';
After that, I want to define an object type where the keys are limited to only certain options from this Union:
// Use only 'A' and 'B' from the union
const myObject: { [K in Union]: number } = {
A: 1,
B: 2,
} as const;
I also want to ensure that myObject remains constant so that I can expect the following behavior:
console.log(myObject.A); // Should work fine
console.log(myObject.C); // Should result in an error
However, when I use [K in Union]
, the compiler throws an error stating:
Property 'C' is missing in type '{ readonly A: 1; readonly B: 2; }' but required in type '{ A: number; B: number; C: number; }'.(2741)
Is it possible to select only specific types from the union for the const object?
The goal here is to declare an object that will exclusively have keys corresponding to a subset of specified union types.