2017-09-25 168 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()); 
    } 
}