在这里,我尝试创建一个设置维度的函数。
dims 可以是一个对象数组,也可以只是一个数字。
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']
。有什么办法吗?
答案 0 :(得分:2)
编译器是绝对正确的:如果 dims
是(比如说)一个数字,dims.width
将产生 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)
}
看in the TS docs。他们有很多例子完全涵盖了这种情况,还有更多。而且,它只是一页(较长的)。