Typescript - declare object of type

I have an object defined as:

const dict = {
    "A": "a",
    "B": "b",
    "C": "c"
};

and a type defined as type Capital = "A" | "B" | "C";.
The type that typescript has automatically assign to dict is

const dict: {
    A: string,
    B: string,
    C: string,
}

Now my question is, is there a way to declare dict in a way to use Capital?
Something like const dict: {Capital: string}?

Upvotes: 0

Views: 57

Answers (1)

gurisko
gurisko

Reputation: 1182

You are looking for Record<Keys, Type> type. More info.

Solution for your case:

type Capital = "A" | "B" | "C";
const dict: Record<Capital, string> = {
    "A": "a",
    "B": "b",
    "C": "c"
};

(playground link)

Upvotes: 2

Related Questions