Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
852 views
in Technique[技术] by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...