在下面的代码中,为什么第一个调用会解析catchClass(aClass&)并将临时值作为第二个调用中的参数catchClass(const aClassCatcher&)
#include <iostream>
using namespace std;
class aClassCatcher{};
class aClass{
public:
operator aClassCatcher(){
return aClassCatcher();
}
};
void catchClass(aClass&){
cout << __FUNCSIG__ << endl;
}
void catchClass(const aClassCatcher&){
cout << __FUNCSIG__ << endl;
}
int main()
{
aClass aC;
catchClass(aC); // calls catchClass(aClass&)
catchClass(aClass()); // calls catchClass(const aClassCatcher&)
}
Run Code Online (Sandbox Code Playgroud)
我意识到这个问题并不是特定于打字稿的,但是如果不注释下面的 (B) 行,则会出现错误Property 'length' does not exist on type 'String | Number'。有没有什么方法可以让打字稿知道所有元素现在只是字符串(过滤完成后)?
const array_: (String| Number)[] = [99, "Hello, World!"];
array_.map((e) => {if (typeof e === "string") console.log(e.length)}) // A
// array_.filter((e) => typeof e === "string").map((e) => {console.log(e.length)}) // B
Run Code Online (Sandbox Code Playgroud)