简体   繁体   中英

Typescript share function overload

Let's say I have a function with multiple overloads. Is there any way to "share" the same overloads in a different function?

function getEmployee(id: number): Employee;
function getEmployee(email: string): Employee;
function getEmployee(email: number, name: string): Employee;
function getEmployee (paramOne: string | number, paramTwo?: string ): Employee { 
  return employee;
}

If I want to use the same overloads in other functions, I need to copy all of them manually.

If you want to share types you can do something like this:

interface GetEmployeeFunctionType {
    (id: number): Employee;
    (email: string): Employee;
    (email: number, name: string): Employee;
    (paramOne: string | number, paramTwo?: string): Employee;
}

And then your new function just type it like so:

const newFunction: GetEmployeeFunctionType = (/** your parameters */) => {// implementation}

When you call newFunction it will give you correct intelisense.

As per @Kaca992 answer, I believe it should be altered in a way, since the last signature is not an overload signature but an implementation signature.

interface GetEmployeeFunctionType {
    (id: number): Employee;
    (email: string): Employee;
    (email: number, name: string): Employee;
}

const newFunction: GetEmployeeFunctionType = (paramOne: string | number, paramTwo?: string): Employee => {/* implementation */}

On the other hand, you can always create a higher order function to wrap the signatures:

interface GetEmployeeFunctionType {
    (id: number): Employee;
    (email: string): Employee;
    (email: number, name: string): Employee;
}

function wrap(func: (paramOne: string | number, paramTwo?: string) => Employee): GetEmployeeFunctionType {
    return func;
}

// usage:
const f = wrap((arg1, arg2) => {/* implementation */});

See TypeScript Playgound for that

As of May 2020, syntax for this case is not currently available . There are relevant issues in the TypeScript issue tracker:

Though there are workarounds using interfaces and call signatures as in Kaca992's answer , they do not result in the same method structure as the syntax you requested (and that is proposed in those issues).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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