Skip to content

Can't exclude undefined from indexed Partial with simple guard #31908

Closed
@dgreensp

Description

@dgreensp

TypeScript Version: 3.5.1

Search Terms:

Indexed, Partial, undefined, guard

Code

function getValue<T, K extends keyof T>(partial: Partial<T>, key: K): T[K] | null {
  const value = partial[key]
  if (value !== undefined) {
    return value // error: TypeScript thinks this can be undefined...
  }
  return null
}

Expected behavior:
Inside the if statement, value should have type T[K]. Especially since partial[key] is assignable to T[K] | undefined, and in fact TypeScript reports the type in the error message as T[K] | undefined, inside the if statement! It's like it just doesn't simplify Partial<T>[K] until it tries returning it.

Here is the workaround, which doesn't involve any casting, just hints:

function getValue<T, K extends keyof T>(partial: Partial<T>, key: K): T[K] | null {
  const value: T[K] | undefined = partial[key]
  if (value !== undefined) {
    return value // OK
  }
  return null
}

It would be nice if this hint wasn't necessary.

Actual behavior:

TypeScript complains that T[K] | undefined is not ok to return, even though the type should be T[K].

Playground Link:

(requires strictNullChecks)

https://www.typescriptlang.org/play/#src=function%20getValue%3CT%2C%20K%20extends%20keyof%20T%3E(partial%3A%20Partial%3CT%3E%2C%20key%3A%20K)%3A%20T%5BK%5D%20%7C%20null%20%7B%0D%0A%20%20const%20value%20%3D%20partial%5Bkey%5D%0D%0A%20%20if%20(value%20!%3D%3D%20undefined)%20%7B%0D%0A%20%20%20%20return%20value%20%2F%2F%20error%3A%20TypeScript%20thinks%20this%20can%20be%20undefined...%0D%0A%20%20%7D%0D%0A%20%20return%20null%0D%0A%7D

Related Issues:

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixedFix AvailableA PR has been opened for this issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions