Type 'string | number | boolean' is not assignable to type 'undefined'. Type 'string' is not assignable to type 'undefined'.ts(2322)

Viewed 910

I'm trying to create a partial object that only has certain fields of the full object that meet a criteria. However, I get the subject typescript error message when I try to assign the property. I created a test module to illustrate the concept/problem. Note that this is only to illustrate the problem. It is not the actual code.

type FullObject = {
  id: number
  name: string
  active: boolean
}

type PartialObject = Partial<FullObject>

const myFullObj: FullObject = {
  id: 1,
  name: 'First Object',
  active: true,
}

const myPartialObj: PartialObject = {}

let k: keyof PartialObject

for (k in myFullObj) {
  if (myFullObj[k] !== undefined) myPartialObj[k] = myFullObj[k] // Error here
  if (k === 'name') myPartialObj[k] = myFullObj[k] // No error here
}

Note that it is only the first "if" statement that has the error. After some research and trying various things, I worked around the problem by initializing the partial object to the full object and then deleting properties that did not meet a criteria. Since this is a backwards way of solving the problem, I would prefer to create the partial object with properties that meet criteria.

1 Answers

I came up with the following solution. It clearly illustrates what I am trying to do: if a criteria is met with a source object property, then copy that property into the partial destination object. In this example I'm using "not undefined" as the criteria. In the real code the criteria is more complex.

type FullObject = {
  id: number
  name: string
  active: boolean
}

type PartialObject = Partial<FullObject>

const myFullObj: FullObject = {
  id: 1,
  name: 'First Object',
  active: true,
}

let myPartialObj: PartialObject = {}

let k: keyof PartialObject

for (k in myFullObj) {
  if (myFullObj[k] !== undefined) myPartialObj = { ...myPartialObj, ...Object.fromEntries([[k, myFullObj[k]]]) }
}
console.log(JSON.stringify(myPartialObj, null, '  '))

It seems that there must be a better way to accomplish this. However, the example illustrates what is intended.

Related