打字稿:联合函数参数的类型保护

时间:2019-12-04 13:05:26

标签: typescript

我想按颜色或系列搜索窗口小部件(至少需要一个)。无法编译:

export function widgets(params: {colorId: number} | {seriesId: number}) {
  if (params.colorId){
    // Search widgets by color
  } else {
    // Search widgets by series
  }
}

错误:Property 'colorId' does not exist on type '{ colorId: number; } | { seriesId: number; }'.

我知道我可以这样工作:

type ColorId = { colorId: number };
function isColorId(params: any): params is ColorId {
  return typeof params.colorId === "number";
}
export function widgets(params: { colorId: number } | { seriesId: number }) {
  if (isColorId(params)) {
    // Search widgets by color
  } else {
    // Search widgets by series
  }
}

我正在寻找的是一种更少样板的解决方案。看来应该有一些更优雅的方法。

1 个答案:

答案 0 :(得分:2)

在这种情况下,缩小类型的最短方法是使用in类型防护:

export function widgets(params: {colorId: number} | {seriesId: number}) {
  if ('colorId' in params) {
    params.colorId
    // Search widgets by color
  } else {
    params.seriesId
    // Search widgets by series
  }
}

Playground Link