在打字稿中获取动态键的类型?

getting type of dynamic key in typescript?

我有一个大致如下所示的对象:

const colors = {
    gray: {
        50: "#f9fafb",
        100: "#f3f4f6",
    },
    red: {
        50: "#fef2f2",
        100: "#fee2e2",
        200: "#fecaca",
    }
}

我正在创建一个辅助函数,它 return 是 colors 对象的一种颜色:

interface GetColor {
    (selector: keyof typeof colors, tint: // ...?): // ...?
}

const getColor = (selector, tint) => {
        return colors[selector][tint];
}

如何获得参数的正确类型(根据 selector 值推断 tint)和 return 值?

这是一个使用泛型的内联示例。 playground

const colors = {
    gray: {
        50: "#f9fafb",
        100: "#f3f4f6",
    },
    red: {
        50: "#fef2f2",
        100: "#fee2e2",
        200: "#fecaca",
    }
}

const getColor = <T extends keyof typeof colors, K extends keyof typeof colors[T]>(selector:T, tint:K): typeof colors[T][K] => {
        return colors[selector][tint];
}

const t1 = getColor('gray', 100)
const t2 = getColor('gray', 200) // Argument of type '200' is not assignable to parameter of type '100 | 50'

const t3 = getColor('red', 200)

const t4 = getColor('blue', 100) // Argument of type '"blue"' is not assignable to parameter of type '"gray" | "red"'