microsoft / microsoft/TypeScript

Incorrect union type inference for conjunction with strictNullChecks disabled

Open
#31,789 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: check: Type Inference
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: 3.4.5

Search Terms: union type inference conjunction strictNullChecks

Code

function fn(x: number) {
  return x && 'a'
}

Expected behavior:
Return type of fn should be 0 | 'a'

Actual behavior:
Return type of fn is '' | 'a' if strictNullChecks is disabled

This is causing me an issue with this specific bit of code, where I'm checking window so my code runs both on the browser and on the client:

function fn(x: number): OrientationType | undefined {
  return window && (window.outerWidth > window.outerHeight ? 'landscape-primary' : 'portrait-primary')
}

I can replace the conjunction with a conditional expression, and I know that if strictNullChecks is disabled I should have a fallback for the return value but I'm posting here for the sake of trying to understand if this is working as intended. It also feels weird that my example compiles with strictNullChecks enabled but doesn't compile when it's disabled.

Playground Link: https://www.typescriptlang.org/play/#src=function%20fn(x%3A%20number)%3A%20OrientationType%20%7C%20undefined%20%7B%0D%0A%20%20return%20window%20%26%26%20(window.outerWidth%20%3E%20window.outerHeight%20%3F%20'landscape-primary'%20%3A%20'portrait-primary')%0D%0A%7D

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

Start by reproducing the examples in the linked TypeScript Playground with strictNullChecks disabled and enabled. Trace how the type checker infers the conjunction expression in fn(x: number). Done means the disabled setting produces the expected 0 | 'a' return type without breaking the enabled setting or the window example.

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.