Home > Mobile >  Difference between typescript declaration of type
Difference between typescript declaration of type

Time:05-27

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;

CodePudding user response:

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;
  • Related