Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

get the type of numeric object properties as strings in typescript?

Having an object similar to this:

const obj = {
   1: "one",
   2: "two",
   3: "three",
}

type Keys = keyof typeof obj; // type of Key is 1 | 2 | 3

how do I get Keys to be of type (strings) "1" | "2" | "3" in order to have autocomplete ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could use template literal types

const obj = {
   1: "one",
   2: "two",
   3: "three",
}

type Keys = `${keyof typeof obj}`;
const value: Keys = "1";
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading