小编azw*_*ier的帖子

Typescript - 如何缩小 switch 语句中泛型类型的类型可能性?

我正在尝试编写一个函数,该函数将根据传递的密钥和参数执行特定的计算。我还想强制传递的键和参数之间的关系,因此我使用了带有约束的通用函数:

interface ProductMap {
  one: {
    basePrice: number;
    discount: number;
  },
  two: {
    basePrice: number;
    addOnPrice: number;
  }
}

function getPrice<K extends keyof ProductMap>(key: K, params: ProductMap[K]) {
  switch (key) {
    case 'one': {
      return params.basePrice - params.discount; // Property 'discount' does not exist on type 'ProductMap[K]'.
    }
    case 'two': {
      return params.basePrice + params.addOnPrice;
    }
  }
}

Run Code Online (Sandbox Code Playgroud)

也许我以错误的方式思考这个问题,但似乎打字稿应该能够缩小 switch 语句中的泛型类型。我能让它工作的唯一方法就是克服这种尴尬:

function getPrice<K extends keyof ProductMap>(key: K, params: ProductMap[K]) {
  switch (key) {
    case 'one': {
      const p = params …
Run Code Online (Sandbox Code Playgroud)

generic-function typescript

7
推荐指数
1
解决办法
1705
查看次数

标签 统计

generic-function ×1

typescript ×1