首页 > 解决方案 > 如何在打字稿中组合类型?

问题描述

在这里,我试图创建一个设置尺寸的函数。

暗淡可以是一个对象数组或只是一个数字。


dimensions(
    dims: { width: number; height: number } | Array<number> | number,
  ) {

console.log(dims.width)

}

但是,如果我访问 dims.width 我得到类型错误 width does not exist on property dims with type { width: number; height: number } | Array<number> | number

我该如何解决这个问题?

简单的方法就是这样做dims['width']。有没有其他选择?

标签: typescript

解决方案


编译器是绝对正确的: if dimsis (say) a number, dims.widthwould yield undefined。编译器不允许这样做。您需要缩小类型:

function normalizeDims(
  dims: { width: number; height: number } | Array<number> | number
  ): { width: number; height: number } {
  if (typeof dims === 'number') {
    // in this block the TS compiler knows dims is a number:
    return { width: dims, height: dims };
  }
  if (Array.isArray(dims)) {
    // here the TS compiler knows dims is an Array<number>
    if (dims.length !== 2) throw Error();
    return { width: dims[0], height: dims[1] };
  }
  // here the compiler has narrowed down the type of dims to object
  return dims;
}

function dimensions(
    dims: { width: number; height: number } | Array<number> | number,
  ) {
  const normalized = normalizeDims(dims);
  console.log(normalized.width)
}

查看TS 文档。他们有很多例子可以完全涵盖这种情况等等。而且,它只是一个(较长的)页面。


推荐阅读