I have an object called "Messages", which basically lists different numeric IDs.
Here is an example of the object, with a very similar structure:
const Messages = {
Alpha: 1,
Beta: {
A: 2,
B: 3,
},
Omega: [
4,
5,
6
],
Zeta: {
C: 7,
D: {
E: 8,
F: 9,
}
}
} as const;
I would like to create a type that takes only the IDs, to be more secure when using them.
Normally, I use this object just to get the ID, in a more "contextualized" way, to use it as a function argument.
Example
// function translate(id: number): string
const label = translate(Messages.Beta.A);
Because I can't tell which IDs are valid, I just use the number
type in the functions.
Notes
- IDs will always be positive numbers and integers.
- Changing the object's shape is possible, but because it is a very large object (2300 lines), I prefer to avoid it.
- Because my object is multidimensional, the questions below did not work:
I started using Typescript professionally last month, so I don't even know where to start.
I don't even know if it's possible to do what I want.
However, given the example, I'm expecting a union type with the values highlighted below:
Infered type of example object Messages
Something like that: type Values = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
.