You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Type guard cannot remove undefined from Partial<T>[keyof T] | undefined #45257
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
The issue here is that we only perform control flow analysis for element accesses with literal property names (e.g. obj['foo']). So, no narrowing is performed for obj[key] because it has a computed property name. We could potentially consider narrowing such expressions when the index expression is a reference to a const variable. I'll mark this issue as a suggestion for that (though I wouldn't be surprised if we already have this suggestion).
Actually, sorry, I misread the example. The issue is that the guard value !== undefined doesn't narrow type Partial<T>[keyof T] to T[keyof T]. I'm not sure how feasible it is to do that narrowing, but it is something we could consider.
Reacted by Jason Dent, Simon Chan, Phryxia and Yannick Huard
Activity
puchm commentedon Jul 31, 2021
I am having a similar issue. Here is another example:
The upper one gets the following error at the
obj[key]line:Type 'number' is not assignable to type 'T[Extract<keyof T, string>]'The lower one does not have this issue. This indicates to me that the issue has something to do with the generics.
ahejlsberg commentedon Aug 1, 2021
The issue here is that we only perform control flow analysis for element accesses with literal property names (e.g.
obj['foo']). So, no narrowing is performed forobj[key]because it has a computed property name. We could potentially consider narrowing such expressions when the index expression is a reference to aconstvariable. I'll mark this issue as a suggestion for that (though I wouldn't be surprised if we already have this suggestion).ahejlsberg commentedon Aug 1, 2021
Actually, sorry, I misread the example. The issue is that the guard
value !== undefineddoesn't narrow typePartial<T>[keyof T]toT[keyof T]. I'm not sure how feasible it is to do that narrowing, but it is something we could consider.ilyakonrad commentedon Mar 31, 2025
I have a similar issue.