3

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 ?

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

5 Comments

Awesome. as const solves the question. I've struggling to understand why typescript was returning only the value type and not the string const instead. Thanks man!
AwesomeType is equivalent to Record<string,string> in this case. I think he wants AwesomeType to be Record<string, "FIRST" | "SECOND" | "THIRD">. I added example in your code. Playgroud
@SubatoPatnaik, no the desired type is type AwesomeType = 'FIRST' | 'SECOND' | 'THIRD'. Type which represents all possible object values, not the object itself
@AlekseyL. Could you give an example with the playground? Btw I like your answer.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.