0

Is it possible to extract the "keys" of a type like i would do with an object and save use them (storing in a variable, mapping, etc)?

consider the object variant:

const obj = { 0: 'a', 1: 'b', 2: 'c' };
const objWithKeys = Object.keys(obj); 
console.log(objWithKeys); // console output: ['0', '1', '2']

can i do the same somehow for a type and then use those keys for something like a dropdown menu?

type scheme = "dhcp" | "static";
const schemeItems = Object.keys(scheme); 
const console.log(schemeItems); // would like to have ["dhcp","static"]

Is this somehow possible to get the desired results and if not why and what should you do instead?

drecunion
  • 121
  • 8
  • 1
    Related: https://stackoverflow.com/questions/44480644/string-union-to-string-array/45486495#45486495 – Caramiriel Dec 08 '20 at 12:58
  • 1
    You can only derive a type from a value, not the other way around: `const SCHEME = ["dhcp", "static"] as const; type Scheme = typeof SCHEME[number]` – Aleksey L. Dec 08 '20 at 13:11
  • @AlekseyL. seems right to me but can you explain why you added [number] to the typeof SCHEME assignment? – drecunion Dec 08 '20 at 13:18
  • 1
    `[number]` is needed to query the tuple's item type (to get the union of all values) – Aleksey L. Dec 08 '20 at 14:32

1 Answers1

0

UPDATED

It is impossible to do in TypeScript, since type scope and variables scope are different scopes.

You can even define same name for variable and type and it will work perfectly fine

type age=number;
const age = 'efr'.