Sam
Sam

Reputation: 525

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?

Upvotes: 2

Views: 55

Answers (1)

axtck
axtck

Reputation: 3965

Since TypeScript 4.1, it is possible to use Template Literal Types.

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

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

Upvotes: 5

Related Questions