Home > Net >  How to pass object with different property name to a same function that can accept that paramemters
How to pass object with different property name to a same function that can accept that paramemters

Time:06-01

we updated object property that a function accept but some function in other files still accept old parameter, so how to call that function that can be valid for both type a functions here is a just example

export interface oldTypeObject {
  type: string;
  name: string;
}

export interface newTypeObject {
  type: string;
  title: string;
}

and functions are

function1(data:oldTypeObject ){
 //somecode
}

function2(data:newTypeObject  ){
 //somecode
}

so now I want to call any function with same parameter like

function1({type:"Type",title|name : "Any Name or title"});
function2({type:"Type",title|name : "Any Name or title"});

There is anyway to do so in javascript/Typscript?

CodePudding user response:

You can add the property that is deprecated as optional to the new type of change the oldTypeObject to add title

export interface newTypeObject or oldTypeOject {
  type: string;
  title: string;
  name?: string;
}

CodePudding user response:

you could use a multi typing like this to ensure that it is one or the other.

functionH(data: oldTypeObject | newTypeObject) {
    if ((data as oldTypeObject).name) {
        function1(data as oldTypeObject);
    } else {
        function2(data as newTypeObject);
    }
}

While being a bit bulkier then @Alexanders solution it is the stricter typed one which might be what you are after.

CodePudding user response:

I think you're looking for function overloads

export interface oldTypeObject {
  type: string;
  name: string;
}

export interface newTypeObject {
  type: string;
  title: string;
}

function handleData(data: newTypeObject): void;
function handleData(data: oldTypeObject): void;
function handleData(data: any): void {
 console.log(data.type)
  if (data.name) {
    console.log(data.name)
  }
  if (data.title) {
    console.log(data.title)
  }
}

const a = {
  type: 'hello',
  name: 'fizz'
}

const b = {
  type: 'goodbye',
  title: 'buzz'
}

handleData(a);
handleData(b);
// no errors
  • Related