Home > Software engineering >  How to use object as parameteres in Typescript?
How to use object as parameteres in Typescript?

Time:01-07

I want to write a Typescript function, that takes two object parameteres without previously knowing the keys of each object.

I am trying to convert this function from JS to TS

function shallowEqual(object1, object2) {
  const keys1 = Object.keys(object1);
  const keys2 = Object.keys(object2);
  if (keys1.length !== keys2.length) {
    return false;
  }
  for (let key of keys1) {
    if (object1[key] !== object2[key]) {
      return false;
    }
  }
  return true;
}

Thanks in advance :-)

CodePudding user response:

I think you can do in below way that will check equality of objects

type TObject = {
  [key in string]?: string  | string[] | object;
}


function shallowEqual(object1: TObject, object2: TObject) {
  return JSON.stringify(object1) === JSON.stringify(object2);
}

CodePudding user response:


shallowEqual(object1: any, object2: any): boolean {
    return JSON.stringify(object1) === JSON.stringify(object2);
  }

OR

shallowEqual(object1: any, object2: any): boolean {    
    const keys1 = Object.keys(object1);
    const keys2 = Object.keys(object2);
    if (keys1.length !== keys2.length) {
      return false;
    }
    for (let key of keys1) {
      if (object1[key] !== object2[key]) {
        return false;
      }
    }
    return true;
  }
  • Related