简体   繁体   中英

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;

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 number | string .

But I think that what you actually want is to end up with this type black | brown 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM