When attempting to create a partial object with specific fields from a full object that meet certain criteria, I encountered a TypeScript error message. To better explain this issue, I designed a test module to showcase the concept/problem without using 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 occurs here
if (k === 'name') myPartialObj[k] = myFullObj[k] // No error here
}
The error mentioned above only arises within the first "if" statement. Through research and experimentation, I found a workaround by initializing the partial object as the full object and then removing properties that do not align with the criteria. However, I view this solution as inefficient and would prefer to directly create a partial object consisting of properties that satisfy the criteria.