2017-09-25 129 views
0

如何让我的打字稿编译器很快乐,而不必更改我在函数测试中收到的接口和typeof参数。打字稿铸造

错误功能测试: -

"Property 'method2' does not exist on type 'xyz'. Did you mean 'method1'?"

interface xyz { 
 
    method1(): string; 
 
} 
 

 
class abc implements xyz { 
 
    method1() { 
 
     return "abc"; 
 
    } 
 
    method2() { 
 
     return "new method"; 
 
    } 
 
} 
 

 
function test(arg: xyz) { 
 
    alert(arg.method2()); 
 
}

Link

+0

你能解释一下编译器是什么不开心的呢? – evolutionxbox

+0

唯一的选择是添加'method2'作为界面的一部分 –

+0

你的问题是什么?什么是编译器错误?你想达到什么目的? – k0pernikus

回答

1

其实你不能。

为什么?

要使代码通过编译器,您需要将method2添加到接口xyz中,或将类型参数更改为接受类型abc。但你也不想要。

1

当你要访问其他领域可以使用一种类型的后卫改变,在编译器中看到的类型:

function isAbc(arg: xyz | abc): arg is abc { 
    return (<abc>arg).method2 !== undefined; 
} 

function test(arg: xyz) { 
    if (isAbc(arg)) { 
     // here the type of `arg` is `abc` 
     alert(arg.method2()); 
    } 
}