I have a Typescript array that contains two classes
StripeCardModel | StripeBankModel
which both extend
StripePaymentModel
Now I am finding a certain class from the array that can contain two classes and then I want to use the function achAccountInterfaceObject
on the found class, because if I have found that class, then it is certainly an instance of StripeBankModel
.
let bankPaymentMethod = this.user.stripePaymentMethods.find( paymentMethod => paymentMethod instanceof StripeBankModel );
if ( bankPaymentMethod ) {
this.bankAccount = bankPaymentMethod.achAccountInterfaceObject;
}
Typescript on the other hand tends to disagree with this and give me a compile time error:
Property 'achAccountInterfaceObject' does not exist on type 'StripeCardModel | StripeBankModel'.
Property 'achAccountInterfaceObject' does not exist on type 'StripeCardModel'.
Could anyone please explain to me how I can write normal code with multityped arrays in typescript without getting these compile time errors?
I have had similar problems with switch cases as like
function abc() : Foo|Boo {
switch ( a.constructor )
{
case "Foo":
a.boo();
case "Bar":
a.doo();
}
}
I want to make good code, but typescript is just not letting me do this here. I dont want to break up my code into multiple functions based on class, if the classes are inherited from the same subtree or have similar functionality.
如果没有人提供更bankPaymentMethod
解决方案,则强制转换bankPaymentMethod
将抑制编译器错误。
this.bankAccount = (<StripePaymentModel>bankPaymentMethod).achAccountInterfaceObject;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.