Typescript: Union Type as interface

2019-09-09 20:12发布

问题:

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.

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

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

回答1:

Use type aliases:

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


回答2:

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