I am working with an object named "Messages" that contains various numeric IDs.
Below is a snippet that represents the structure of the object:
const Messages = {
Alpha: 1,
Beta: {
A: 2,
B: 3,
},
Omega: [
4,
5,
6
],
Zeta: {
C: 7,
D: {
E: 8,
F: 9,
}
}
} as const;
My goal is to define a type that specifically captures these IDs, ensuring secure usage.
Typically, I utilize this object to retrieve the ID in a contextual manner for functions.
For example:
// function translate(id: number): string
const label = translate(Messages.Beta.A);
Since I cannot ascertain valid IDs, I resort to using the generic number
type in functions.
Specifications:
- The IDs are always positive integers.
- Although modifying the object's structure is feasible, due to its extensive size (2300 lines), I aim to avoid such alterations.
- As my object is multidimensional, conventional solutions like those referenced below have not proven effective:
- Create a type constructed with values of an object
- How to create a type with values from plain object?
Taking my recent plunge into professional use of Typescript, I find myself unsure how to proceed.
Uncertain if my objective is even attainable, I envision generating a union type embodying the highlighted values:
Infered type of example object Messages
An approximation might resemble:
type Values = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
.