typescript - 如何在打字稿中组合类型?
问题描述
在这里,我试图创建一个设置尺寸的函数。
暗淡可以是一个对象数组或只是一个数字。
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']
。有没有其他选择?
解决方案
编译器是绝对正确的: if dims
is (say) a number, dims.width
would 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 文档。他们有很多例子可以完全涵盖这种情况等等。而且,它只是一个(较长的)页面。
推荐阅读
- angular - 如何以反应形式创建复杂的表单控件
- python - 为什么 scikit-learn r2 得分为零?
- python - Heroku 通过外部 SMTP 服务器发送邮件
- python - 是否有可能在字典中查找字符串?
- drupal - 在没有编辑权限的情况下翻译内容时访问菜单设置
- java - 用于容器化应用程序的 Open JDK 和 Oracle JDK 之间的区别
- java - 我的 Spring Boot 项目有映射异常
- javascript - 在 React 中将数组转换为组件
- html - 在悬停时显示包含整个文本的吐司
- python - 使用Openpyxl将IF公式插入Excel后出现“@”符号