【问题标题】:getting type of dynamic key in typescript?在打字稿中获取动态键的类型?
【发布时间】:2022-01-25 12:54:49
【问题描述】:

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

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

我正在创建一个从 colors 对象返回颜色的辅助函数:

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

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

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

【问题讨论】:

  • 都是对象属性,所以都是字符串。
  • 我知道,我的意思是,有没有一种方法可以根据 selector 值而不只是类型编号来推断 tint 的类型为 (50 | 100 | etc...)

标签: typescript types


【解决方案1】:

这是一个使用泛型的内联示例。 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"'

【讨论】:

    猜你喜欢
    • 2020-03-09
    • 1970-01-01
    • 2022-12-19
    • 2022-12-10
    • 2020-05-21
    • 1970-01-01
    • 1970-01-01
    • 2020-05-09
    • 2020-01-23
    相关资源
    最近更新 更多