Ad

Is It Possible To Implement One Of Two Signatures In Typescript?

- 1 answer

For example, let's say I want to accept an array of a specific type (say User) or an array of arrays of Users as a parameter.

In other words, I want to do something like this:

interface arrayTypeOne {...}
interface arrayTypeTwo {...}

export class MyClass {

    myMethod(args:MustBeOneOrTwo) {

    }
}

The flexibility is valuable to consumers of the API, so I don't think it's a good idea to break it into two methods. On the other hand, I'd really like to declare a type more specific than all.

Ideas?

Ad

Answer

More recent versions of Typescript have introduced the concept of union types, where you can specify that a parameter/variable is one of a list of types.

In your example, you would do:

interface arrayTypeOne {...}
interface arrayTypeTwo {...}

export class MyClass {

    myMethod(args: arrayTypeOne | arrayTypeTwo) {

    }
}
Ad
source: stackoverflow.com
Ad