首页 文章

从typescript联合类型数组调用函数

提问于
浏览
0

我有一个包含两个类的Typescript数组

StripeCardModel | StripeBankModel

两者都延伸

StripePaymentModel

现在我从数组中找到一个可以包含两个类的某个类,然后我想在找到的类上使用函数 achAccountInterfaceObject ,因为如果我找到了这个类,那么它肯定是 StripeBankModel 的一个实例 .

let bankPaymentMethod = this.user.stripePaymentMethods.find( paymentMethod => paymentMethod instanceof StripeBankModel );
if ( bankPaymentMethod ) {
    this.bankAccount = bankPaymentMethod.achAccountInterfaceObject;
}

另一方面,Typescript倾向于不同意这一点,并给我一个编译时错误:

Property 'achAccountInterfaceObject' does not exist on type 'StripeCardModel | StripeBankModel'.
Property 'achAccountInterfaceObject' does not exist on type 'StripeCardModel'.

任何人都可以向我解释如何在打字稿中用多字节数组编写普通代码而不会出现这些编译时错误?

我对切换案例有类似的问题

function abc() : Foo|Boo {
    switch ( a.constructor )
    {
        case "Foo":
            a.boo();

        case "Bar":
            a.doo();
    }
}

我想制作好的代码,但打字稿只是不让我这样做 . 如果类继承自相同的子树或具有类似的功能,我不想将我的代码分解为基于类的多个函数 .

1 回答

  • 1

    如果没有人有更优雅的解决方案,那么转换 bankPaymentMethod 将抑制编译器错误 .

    this.bankAccount = (<StripePaymentModel>bankPaymentMethod).achAccountInterfaceObject;
    

相关问题