Home > Back-end >  How do I overload a function with named parameters in TypeScript?
How do I overload a function with named parameters in TypeScript?

Time:01-16

I have a function which I want to be able to pass normal arguments and keyword (named) arguments. Yet, whenever I try doing the overload I get an error.

I tried overloading the function this way:

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

Where:

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

Of course this is a simplification of a bit more complicated case; but the idea here is to be able to pass name and age, for example; without having to move surname or doing the following:

myFunc("Foo", null, 111);

And just doing:

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

I get the following error:

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 link:

Edit: as @jonrsharpe's pointed:

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

Forgot to mark surname and age as optional in the final declaration.

CodePudding user response:

Try this way

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

  • Related