function copyFields<T>(target: T, source: Partial<T>): T {
for (let id in source) {
target[id] = source[id]; // Error
}
return target;
}
let x = { a: 1, b: 2, c: 3, d: 4 };
copyFields(x, { b: 10, d: 20 });
Code above occurs the error Type 'T[Extract<keyof T, string>] | undefined' is not assignable to type 'T[Extract<keyof T, string>]'. Type 'undefined' is not assignable to type 'T[Extract<keyof T, string>]'.
Doesn't source always a part of target?
What's the problem?
CodePudding user response:
The type Type 'T[Extract<keyof T, string>] | undefined can be undefined, which cannot be assigned to type Type 'T[Extract<keyof T, string>].
Your input source may have a property that has been explicitly set to undefined, which would not be able to be assigned to the equivalent property on target.
You should check for this case, though it looks like this condition isn't enough for TypeScript to determine that it's definitely not undefined. However, you can then apply TypeScript's non-null assertion operator to make sure TypeScript realises this means the property is not undefined:
function copyFields<T>(target: T, source: Partial<T>): T {
for (let id in source) {
const sourceProp = source[id];
if (typeof sourceProp !== 'undefined') {
target[id] = sourceProp!; // No error here
}
}
return target;
}
let x = { a: 1, b: 2, c: 3, d: 4 };
copyFields(x, { b: 10, d: 20 });
