如何在TypeScript中重载带有命名参数的函数?

yjghlzjz  于 2023-01-18  发布在  TypeScript
关注(0)|答案(1)|浏览(139)

我有一个函数,我希望它能够传递普通参数和关键字(命名)参数。然而,每当我尝试重载时,我得到一个错误。
我试着这样重载函数:

function myFunc({name, surname, age}: myFuncParams): string;
function myFunc(name: string, surname?: string, age?: number): string;
function myFunc(nameOrObj: string | myFuncParams, surname?: string, age?: number): string {
// do something and return a string
  return ""
};

其中:

interface myFuncParams {
  name: string,
  surname?: string,
  age?: number
}

当然这是一个更复杂的例子的简化;但这里的想法是能够传递姓名和年龄,例如;而无需更改姓氏或执行以下操作:

myFunc("Foo", null, 111);

只是在做:

myFunc({name:"Foo", age:111});

出现以下错误:

function myFunc({name, surname?, age?}: myFuncParams): string;
//        ^: This overload signature is not compatible with its implementation signature. (2394)
function myFunc(name: string, surname?: string, age?: number): string;
function myFunc(nameOrObj: string | myFuncParams, surname?: string, age?: number): string {
// do something and return a string
  return ""
};

typescript Playground链接:
编辑:正如@jonrsharpe指出的:

function myFunc({name, surname, age}: myFuncParams): string;
function myFunc(name: string, surname?: string, age?: number): string;
function myFunc(nameOrObj: string | myFuncParams,surname?: string,age?: number): string {
  return ""
};

忘记在最终声明中将姓氏和年龄标记为可选。

wlsrxk51

wlsrxk511#

试试这边

function myFunc(opts: myFuncParams): string;
function myFunc(name: string, surname?: string, age?: number): string;
function myFunc(nameOrObj: string | myFuncParams, surname?: string, age?: number): string {
// do something and return a string
  return ""
};

相关问题