Marcio Pamplona
Marcio Pamplona

Reputation: 33

How to create a type with values from plain object?

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

Answers (2)

Aleksey L.
Aleksey L.

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"

Playground

Upvotes: 3

Yoel
Yoel

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

Related Questions