Skip to content

Non-nullish assertion over property of generic object not respected #44698

Closed
@LinusU

Description

@LinusU

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:

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

⏯ Playground Link

Playground link with relevant code

💻 Code

type PartialNonNullable<T> = { [P in keyof T]?: NonNullable<T[P]> }

function withoutNullishValues<T extends object> (input: T): PartialNonNullable<T> {
  const result: PartialNonNullable<T> = {}

  for (const key of Object.keys(input) as (keyof T)[]) {
    if (input[key] != null) result[key] = input[key]
  }

  return result
}

🙁 Actual behavior

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions