microsoft / microsoft/TypeScript

NonNullable isn't narrowing down object values' types for optional properties

Open
#28,374 11 comments 9 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Domain: Mapped Types Experience Enhancement Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: 3.2.0-dev.20181106

Search Terms:
NonNullable object
NonNullable object values

Code

Run the following code via tsc --no-emit --strict test.ts:

interface P {
  color?: 'red' | 'green';
}

type RequiredP = {
  [K in keyof P]: NonNullable<P[K]>;
}

declare const p: RequiredP;
const color: 'red' | 'green' = p.color;

Expected behavior:

The resulting type should not allow undefined for the value at a property color.

Actual behavior:

undefined is still allowed. Using the NonNullable type doesn't seem to have any effect.

Playground Link: Note: you need to enable strictNullChecks manually!
https://www.typescriptlang.org/play/#src=interface%20P%20%7B%0D%0A%20%20color%3F%3A%20'red'%20%7C%20'green'%3B%0D%0A%7D%0D%0A%0D%0Atype%20RequiredP%20%3D%20%7B%0D%0A%20%20%5BK%20in%20keyof%20P%5D%3A%20NonNullable%3CP%5BK%5D%3E%3B%0D%0A%7D%0D%0A%0D%0Adeclare%20const%20p%3A%20RequiredP%3B%0D%0Aconst%20color%3A%20'red'%20%7C%20'green'%20%3D%20p.color%3B%0D%0A

Related Issues:

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the example with TypeScript 3.2.0-dev.20181106 using tsc --no-emit --strict test.ts, then compare it with the current compiler and the linked Playground. Investigate how mapped types, optional properties, and NonNullable are handled; done means the declared color assignment rejects undefined while preserving the 'red' | 'green' type.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.