如何在这种情况下使用TypeScript查找类型?

对不起,这个标题没用,但是我真的不知道该怎么称呼它。

我有一个枚举,我想将每个枚举的条目都匹配为一个类型。我这样做是为了使函数的参数可以根据第一个参数动态更改。一个例子:

enum Enum {
    A,
    B,
    C
}

interface TypeMap {
    [Enum.A]: number,
    [Enum.B]: string,
    [Enum.C]: boolean
}

function doSomething<K extends Enum>(a: K, b: TypeMap[K]) {
    //
}

The type system works correctly when calling doSomething, for example: doSomething(Enum.A, 5) works, but doSomething(Enum.A, "hello") doesn't. However, what I can't get to work is this:

function doSomething<K extends Enum>(a: K, b: TypeMap[K]) {
    if (a === Enum.A) {
        let num: number = b;
    }
}

Typescript errors out at the assignment to num, but clearly, CLEARLY, it should work. If a is Enum.A, then b has to BY DEFINITION be number, right? What am I doing wrong? How do I get this to work?

评论