[英]Typescript casting
How can I make my typescript compiler happy without changing the interface and typeof argument I'm receiving in function test. 如何在不更改函数测试中收到的接口和typeof参数的情况下使我的Typescript编译器满意。
Error in function test:- 功能测试错误:-
"Property 'method2' does not exist on type 'xyz'. Did you mean 'method1'?"
“类型'xyz'不存在属性'method2'。您是说'method1'吗?”
interface xyz { method1(): string; } class abc implements xyz { method1() { return "abc"; } method2() { return "new method"; } } function test(arg: xyz) { alert(arg.method2()); }
You can use a type guard to change the type that is seen at the compiler when you want to access the other fields: 当您要访问其他字段时,可以使用类型保护来更改在编译器中看到的类型:
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());
}
}
Actually you can't. 其实你做不到
Why ? 为什么呢
To make your code to pass compiler you need either add the method2
into the interface xyz
or change the type parameter to accept the type abc
. 要使代码通过编译器,您需要将
method2
添加到接口xyz
或更改type参数以接受abc
类型。 But you don't want neither. 但是你都不想要。
After going through documents, got to know about Type assertions, which helped me to compile that small piece of code successfully. 浏览完文档后,了解了类型断言,这有助于我成功地编译那小段代码。
function test(arg: xyz) {
var arg2 = <abc>arg;
alert(arg2.method2());
}
https://www.typescriptlang.org/docs/handbook/basic-types.html https://www.typescriptlang.org/docs/handbook/basic-types.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.