Reputation: 33
I had a object like this:
const myObject = {
0: 'FIRST',
10: 'SECOND',
20: 'THIRD',
}
I want to create a type with this object values, like this:
type AwesomeType = 'FIRST' | 'SECOND' | 'THIRD';
How to achieve this ?
Upvotes: 3
Views: 176
Reputation: 37986
To get the variable (object) type you can use typeof
operator. To prevent literal types widening you can use as const
assertion:
const myObject = {
0: 'FIRST',
10: 'SECOND',
20: 'THIRD',
} as const;
type Values<T> = T[keyof T];
type AwesomeType = Values<typeof myObject>; // "FIRST" | "SECOND" | "THIRD"
Upvotes: 3
Reputation: 7985
Do it this way
type AwesomeType = 'FIRST' | 'SECOND' | 'THIRD';
type MyType = Record<number, AwesomeType>
const myObject: MyType = {
0: 'FIRST',
10: 'SECOND',
20: 'THIRD',
}
see in this playground
Upvotes: 2