简体   繁体   中英

Dynamic copy only some properties between 2 same typed object in Typescript

Hello All I'm getting tsc compilation error when try to merge 2 objects dynamically: I try to merge only some properties of the object don't want to copy all of them. The example below is a method in a typescript Class that implements the same interface of the parameter received, "iUser" , so "this" is the same type object of the received parameter( "userSave" )

expample:

 updatefromUser(userSave: iUser) {
            let propToValidate: (keyof iUser)[]
            propToValidate = ["Country", "City", "State", "Zip", "VATnr", "Language"]
            let updateData: boolean = false;
            propToValidate.forEach(ele => {
                if (this[ele] != userSave[ele]) {
                    this[ele] =  userSave[ele]
                    updateData = true
                }
            });
            return updateData
        }

the compilation error says:

error TS2322: Type 'string | string[] | Date | iAuthUserId[] | iAuthUser[] | null' is not assignable to type 'string & iAuthUserId[] & iAuthUser[] & Date & string[]'. Type 'null' is not assignable to type 'string & iAuthUserId[] & iAuthUser[] & Date & string[]'. Type 'null' is not assignable to type 'string'. 112 this[ele] = userSave[ele] ~~~~~~~~~

Anyone knows how to do this dynamically?

Maybe there are some properties in a class definition that are more strict than those in iUser interface? Because your error tells something similar to this. For example, consider the code:

interface iUser {
  id: string,
  name: string|null
}

class User implements iUser {
  id: string;
  name: string;

  update(userSave: iUser) {
    let propToValidate: (keyof iUser)[]
    propToValidate = ["id", "name"]
    let updateData = false;
    propToValidate.forEach(ele => {
      if (this[ele] != userSave[ele] && typeof this[ele] === typeof userSave[ele]) {
          this[ele]=  userSave[ele]
          updateData = true
      }
    });
    return updateData
  }
}

iUser interface allows the name to be null, but the class does not. There will be the error similar to yours, unfortunately it does not tell us what exactly property of iUser is not compatible with User class.

Possible solution would be to make all properties the same, or check those properties that are different in iUser and in the class, something like this:

...
propToValidate.forEach(ele => {
  if (this[ele] != userSave[ele] && typeof this[ele] === typeof userSave[ele]) {
      if (ele === 'name') {
        this[ele] =  userSave[ele] ?? ''
      }
      else {
        this[ele]=  userSave[ele]
      }
      updateData = true
  }
});
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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