Makoto
Makoto

Reputation: 775

Difference between typescript declaration of type

I have this hash:

const COLOR_TO_VALUE: {[key: string]: number} = {
    black: 0,
    brown: 1,
...
}

If I want to reference the keys in a function such as:

export function decodedResistorValue(colorBands: Color[]){
...
}

What is the difference between:

type Color = typeof COLOR_TO_VALUE[string];

and

type Color = keyof typeof COLOR_TO_VALUE;

Upvotes: 0

Views: 37

Answers (1)

Radu Diță
Radu Diță

Reputation: 14171

The first syntax will get the type of all the values for which the keys are string. In this case this is number.

The second one will get the type of all the keys for the type of COLOR_TO_VALUE. You may expect that to be string, but because of how objects work in JS, you may access it using string index or numeric one, the type is actually number | string.

But I think that what you actually want is to end up with this type black | brown. You can do this by letting TS infer the type and use keyof typeof. Something like this:

const COLOR_TO_VALUE = {
    black: "0",
    brown: "1",
}

type Color = keyof typeof COLOR_TO_VALUE;

Upvotes: 1

Related Questions