本文介绍了打字稿:联合类型作为接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种情况下,我需要一个函数来接受各种不同的类型.它们将由函数中的类型保护分隔.所以我使用的是这样的联合类型:

I have a situation where I need a function to accept a variety of different types. They will be separated by type guards within the function. So I am using a Union Type like this:

function(param: TypeA | TypeB): void {
    let callback: (param: TypeA | TypeB): void = () => {};

    if (isTypeA(param)) {
        callback = doSomethingWithTypeA;
    } else if (isTypeB(param)) {
        callback = doSomethingWithTypeB;
    }

    return callback(param);
}

函数doSomethingWithTypeA仅接受typeA,依此类推.

Where the function doSomethingWithTypeA only accepts typeA and so on.

正如您所看到的,总是写出(TypeA | TypeB)非常冗长,特别是因为在我的实际代码中它有两种以上.

As you can see, always writing out (TypeA | TypeB) is very verbose, especially since it's more than two types in my actual code.

是否有某种方法可以创建(TypeA | TypeB)的接口?
还是有其他方法可以实现这一目标?

Is there some way to create an interface that is (TypeA | TypeB) ?
Or is there some other way to achieve this?

推荐答案

使用类型别名:

type YourType = TypeA | TypeB // | ... and so on

这篇关于打字稿:联合类型作为接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-22 07:03