Dmitry Reutov
Dmitry Reutov

Reputation: 3032

How to update an object with keys from another object in Typescript?

i am newcomer to typescript and have a following problem

I have an object of type Man with set of keys

type Man = { name: string; surname: string; age: number }
type ManKey = keyof Man

const johnSmith: Man = { name: 'John', surname: 'Smith', age: 99 }

now i have an object with arbitrary properties, some of them can intersect with Man's keys, then we should use their values to update johnSmith values. For instance:

const newProps = { religion: 'hindu', age: 30 }

in this example age should be recognized as Man's property and 30 should be written to johnSmith variable. Something like this (such code of course doesn't work)

for (let key in newProps) 
  if (key instanceof ManKey)
    johnSmith[key] = newProps[key]

Thanks in advance

PS sandbox with example https://codesandbox.io/s/elated-ardinghelli-db6kv?file=/src/App.tsx:0-478

Upvotes: 1

Views: 608

Answers (1)

Aplet123
Aplet123

Reputation: 35512

Yuo're close, but you shoul duse key in johnSmith instead of key instanceof ManKey:

for (const key in newProps) {
    if (key in johnSmith) {
        johnSmith[key] = newProps[key];
    }
}

EDIT: It appears that typescript still suffers from the inability to infer for...in types, so for now you'll have to do the ugly method of casting the key:

for (let key in newProps) {
  if (key in johnSmith) {
    let castKey = key as (keyof typeof newProps & keyof typeof johnSmith);
    johnSmith[castKey] = newProps[castKey];
  }
}

Upvotes: 1

Related Questions