简体   繁体   English

打字稿:联合类型作为接口

[英]Typescript: Union Type as interface

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);
}

Where the function doSomethingWithTypeA only accepts typeA and so on. 函数doSomethingWithTypeA仅接受typeA,依此类推。

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) ? 有什么方法可以创建(TypeA | TypeB)接口?
Or is there some other way to achieve this? 还是有其他方法可以做到这一点?

使用类型别名

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

How about creating an interface: 如何创建界面:

interface MyType {
}

class TypeA implements MyType {
}

class TypeB implements MyType {
}

Then you can check it in the method: 然后可以在方法中检查它:

function(param: MyType): void {
    let callback: (param: MyType): void = () => {};

    if (param instanceof TypeA) {
        callback = doSomethingWithTypeA;
    } else if (param instanceof TypeB) {
        callback = doSomethingWithTypeB;
    }

    return callback(param);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM