以下为
this
问题,有以下代码:(见注释行
//ERROR: ts(2358)
)
const w = ((mat: Float32Array | Vec4) => {
if (mat instanceof Float32Array) {
const sizeIsOk = mat.length == 4;
if (sizeIsOk) {
return <number>mat[4];
} else {
console.log('point does not have 4 coordinates. 4th default is 1 if not defined');
return mat.length > 4 ? mat[3] : 1;
}
} else if (mat instanceof Vec4) { //ERROR: ts(2358)
}
return 0;
})(matrix);
如果左手边必须是“any”、对象类型(或我认为是类实例)或类型参数类型,我就可以了,
不仅在
else
条款
.
在lambda中添加“any”类型就解决了这个问题。如果在函数参数类型union中添加它是不起作用的,这也让我感到惊讶,因为任何类型都必须添加到lambda参数中,而函数中传递的参数已经定义了其union类型。
只需在λ中添加任何类型的解决方案代码:
function foo(matrix: Float32Array | Vec4) { // Any in the union here does not work!
const w = ((mat: Float32Array | Vec4 | any) => {
if (mat instanceof Float32Array) {
const sizeIsOk = mat.length == 4;
if (sizeIsOk) {
return <number>mat[4];
} else {
console.log('point does not have 4 coordinates. 4th default is 1 if not defined');
return mat.length > 4 ? mat[3] : 1;
}
} else if (mat instanceof Vec4) {
}
return 0;
})(matrix);
}
我认为这与typescript如何处理实例的类型检查有关,但无法理解这是否是设计和正常的行为以及原因。
总之,为什么
instanceof
不会在else子句中编译,并且必须在lambda参数中添加任何类型,其中传入的参数已经在其各自的类型中定义?
旁注:
1.-在编辑器中复制粘贴代码可能会更快地理解我的观点,而不是深入讲解所解释的问题,因为它非常直接,但很难用文字正确解释。
2.如果你好奇或想深入这个有趣的话题,可以找一些我看过的资源,但这些资源并没有让我满意地读完这篇文章。资源
one
和
two