如何在 typescript 映射方法中使用 javascript 查找表?

and*_*oss 4 javascript typescript

如何在 map 函数中使用简单的 JavaScript查找表(即映射本身)?即我如何摆脱这个"code"字段(从这里借用),并仅使用方法内的查找表map

const Resistors = {
    "black": 0,    "brown": 1,    "red": 2,
    "orange": 3,   "yellow": 4,   "green": 5,
    "blue": 6,     "violet": 7,   "grey": 8,
    "white": 9,

    // Why not Resistors[color]
    "code" : (color: string) => {
        function valueOf<T, K extends keyof T>(obj: T, key: K) {
            return obj[key];
        }
        return valueOf(Resistors, color as any);
    }
}
class ResistorColor {
    private colors: string[];
    constructor(colors: string[]) { this.colors = colors; }
    value = () => {
        return Number.parseInt(
            this.colors
                  .map(Resistors.code) // How can i get rid of .code here?
                  .join("")
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

Jus*_*ith 7

确切地知道您在寻找什么有点困难,但一目了然……您可以!您应该能够执行以下操作:

const Resistors = {
  black: 0,
  brown: 1,
}
Run Code Online (Sandbox Code Playgroud)

进而...

const numericColorCode = Resistors['black'];
console.log(numericColorCode) // should be 0
Run Code Online (Sandbox Code Playgroud)

现在,有时 TypeScript 编译器会对此类事情变得脾气暴躁。你可能需要做这样的事情来让编译器满意:

const numericColorCode = (Resistors as {[index: string]: number})['black'];
Run Code Online (Sandbox Code Playgroud)

至于下面的问题 - 使用Object.keysArray.join!

const allTheColors = Object.keys(Resistors).join(',');
console.log(allTheColors); // should be 'black,brown'
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!