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
I'm building a function that removes nullish-values from an object. In the code, that is generic over the object, TypeScript doesn't seem to respect my non-nullish assertion:
if(input[key]!=null)result[key]=input[key]
It seems to think that input[key] could possibly be null in the assignment, even though the line is guarded by input[key] != null.
🔎 Search Terms
nullish assertion generics assignment
🕗 Version & Regression Information
This is the behavior in every version I tried, and I reviewed the FAQ for entries about: v4.4.0-dev.20210622, v4.3.4, v4.3.2, v3.3.33
Type 'T[keyof T]' is not assignable to type 'NonNullable<T[keyof T]> | undefined'.
Type 'T[string] | T[number] | T[symbol]' is not assignable to type 'NonNullable<T[keyof T]> | undefined'.
Type 'T[string]' is not assignable to type 'NonNullable<T[keyof T]> | undefined'.
Type 'T[string]' is not assignable to type 'NonNullable<T[keyof T]>'.
Type 'T[keyof T]' is not assignable to type 'NonNullable<T[keyof T]>'.
Type 'T[string] | T[number] | T[symbol]' is not assignable to type 'NonNullable<T[keyof T]>'.
Type 'T[string]' is not assignable to type 'NonNullable<T[keyof T]>'.
🙂 Expected behavior
no errors in type checking
The text was updated successfully, but these errors were encountered:
If you're trying to narrow a generic type (we'll call it T), then TS can typically only represent the narrowing as T & NarrowerType (because within the generic function you don't know precisely what T is). In your case the necessary representation would be T & NOT null, which could only be done if we had negated types. See #4196.
Generics can only be narrowed if they're a union, and T[keyof T] is not a union (it's effectively opaque from the checker's perspective), so no narrowing occurs here.
The implied suggestion here is to produce the narrowed type NonNullable<T[keyof T]> for input[key] inside the if; this is something we've experimented with but it's not as straightforward as it initially seems (at minimum for example, you need a new built-in type for every kind of narrowing, with associated higher-order behavior)
Bug Report
I'm building a function that removes nullish-values from an object. In the code, that is generic over the object, TypeScript doesn't seem to respect my non-nullish assertion:
It seems to think that
input[key]
could possibly be null in the assignment, even though the line is guarded byinput[key] != null
.🔎 Search Terms
nullish assertion generics assignment
🕗 Version & Regression Information
⏯ Playground Link
Playground link with relevant code
💻 Code
🙁 Actual behavior
🙂 Expected behavior
no errors in type checking
The text was updated successfully, but these errors were encountered: