简体   繁体   English

打字稿共享函数重载

[英]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.当您调用 newFunction 时,它会为您提供正确的智能感知。

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.根据@Kaca992 的回答,我认为应该以某种方式对其进行更改,因为最后一个签名不是重载签名而是实现签名。

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请参阅TypeScript Playgound

As of May 2020, syntax for this case is not currently available .截至 2020 年 5 月,此案例的语法目前不可用 There are relevant issues in the TypeScript issue tracker: TypeScript 问题跟踪器中有相关问题:

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).尽管在Kaca992's answer 中有使用接口和调用签名的解决方法,但它们不会产生与您请求的语法相同的方法结构(并且在这些问题中提出)。

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

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