Open
Description
Bug Report
When writing a function to merge object A
with non-undefined values from object B
into C
where A
is of type T
and B is of type Partial<T>
, I came across a situation where the type guard seems to be failing.
🔎 Search Terms
- type guard
- Partial
🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about common-bugs-that-arent-bugs
⏯ Playground Link
Playground link with relevant code
💻 Code
function merge<T>(a: T, b: Partial<T>, keys: (keyof T)[]): T {
const v: T = { ...a };
for (const key of keys) {
const value = b[key];
if (value !== undefined) {
v[key] = value;
}
}
return v;
}
🙁 Actual behavior
There is an error at v[key] = value;
:
Type 'T[keyof T] | undefined' is not assignable to type 'T[keyof T]'.
Type 'undefined' is not assignable to type 'T[keyof T]'.
Clearly value
is NOT undefined
, yet the compiler complains that it is.
🙂 Expected behavior
I would expect that the code compiled.