[英]How to combine types in typescript?
Here I'm trying to create a function that sets dimensions.在这里,我试图创建一个设置尺寸的 function。
the dims could either be an object array or just a number.暗淡可以是 object 阵列或只是一个数字。
dimensions(
dims: { width: number; height: number } | Array<number> | number,
) {
console.log(dims.width)
}
But if I access dims.width I'm getting type error width doesnot exists on property dims with type { width: number; height: number } | Array<number> | number
但是如果我访问 dims.width 我得到类型错误 width does not exist on property dims with type
{ width: number; height: number } | Array<number> | number
{ width: number; height: number } | Array<number> | number
How can I solve this?我该如何解决这个问题?
Easy way is to do like this dims['width']
.简单的方法就是这样做
dims['width']
。 Is there any alternative?有没有其他选择?
The compiler is absolutely right: if dims
is (say) a number, dims.width
would yield undefined
.编译器是绝对正确的:如果
dims
是(比如说)一个数字, dims.width
将产生undefined
。 The compiler doesn't allow that.编译器不允许这样做。 You need to narrow the type:
您需要缩小类型:
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)
}
Look in the TS docs .查看TS 文档。 They have lots of examples that cover exactly this case and many more.
他们有很多例子可以完全涵盖这种情况等等。 And, it's just one (longish) page.
而且,它只是一个(较长的)页面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.