[英]Calling functions from a typescript union type array
I have a Typescript array that contains two classes 我有一个包含两个类的Typescript数组
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
. 现在,我从数组中找到一个可以包含两个类的类,然后我想对找到的类使用
achAccountInterfaceObject
函数,因为如果我找到了该类,那么它肯定是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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.