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 Answers2

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

Aleksey L.
  • 35,047
  • 10
  • 74
  • 84
  • 2
    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! – Marcio Pamplona May 09 '21 at 10:38
  • AwesomeType is equivalent to `Record` in this case. I think he wants AwesomeType to be `Record`. I added example in your code. [Playgroud](https://www.typescriptlang.org/play?#code/MYewdgzgLgBAtgTwPICMBWBTYsC8MDeAUDDAAwBcMA5AGICSASgMoAqVANMTAIwXVMBRAMJIAcgBEOXAEx8qLABKNJnAL4wAhhBihIUANyFCuiCAA2GAHRmQAcwAUUBAAcMIAGbxk6LFACUhk6uMABqGmYArhgQADwsAHwweCwA2gDWGAgeMCwAuoaEQRgwAIIA7tEgcBgsLsV4YZHRMUXZiKiY2PH6MAD0vTAARPTMLIMwAD5DgiIS41ODisqDRiawiJTlldW1wXhEJBow5LSMrFIkKMdUM2IqXMDXSwyShKpAA) – Subrato Pattanaik May 09 '21 at 10:41
  • 1
    @SubatoPatnaik, no the desired type is `type AwesomeType = 'FIRST' | 'SECOND' | 'THIRD'`. Type which represents all possible object values, not the object itself – Aleksey L. May 09 '21 at 10:46
  • @AlekseyL. Could you give an example with the playground? Btw I like your answer. – Subrato Pattanaik May 09 '21 at 10:48
  • 1
    https://www.typescriptlang.org/play?#code/MYewdgzgLgBAtgTwPICMBWBTYsC8MDeAUDDAAwBcMA5AGICSASgMoAqVANMTAIwXVMBRAMJIAcgBEOXAEx8qLABKNJnAL4wAhhBihIUANyFCuiCAA2GAHRmQAcwAUUBAAcMIAGbxk6LFACUhk6uMABqGmYArhgQADwsAHwweCwA2gDWGAgeMCwAuoaEQRgwAIIA7tEgcBgsLsV4YZHRMUXZiKiY2PH6MAD0vTAARPTMLIMwAD5DgiIS41ODisqDRiaw7iAglOWV1bXBeLSMrFQF-TACAB6u2BgAJjAYAE5PIE+U+8VUg1DRUINUGAAS20YBAsC0ECBtjAGhQFhgUBAiLq1B2pj2dSoxnA0BgKA071KFQxNVRh1+0FOQA – Aleksey L. May 09 '21 at 10:50
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

Yoel
  • 7,555
  • 6
  • 27
  • 59