microsoft / microsoft/TypeScript

Type narrowing down on a union type with null results in incorrect type when applying `typeof`

Open
#44,914 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: check: Control Flow
Dominant language
Go
Stars
111k
Forks
14.4k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

Bug Report

🔎 Search Terms

type narrowing down, typeof

🕗 Version & Regression Information

I've tested all versions until 4.4.0 (Nightly)

⏯ Playground Link

https://www.typescriptlang.org/play?ts=4.4.0-dev.20210706#code/C4TwDgpgBAwg9gO2AQwJYIgJygXigbygGNEV0sAuA0SKgIgDM446BfKAH2vAnoCNkmNpygIArgBsJUVgFgAUAoZiERYKkRRgEAM7AAFOjBjgVeEjQZMASgIKoDqKgZRDCY8AB0JC+UwB+TxpoHFCoAHImOHDbfHtHBIB6RKgAdzhMAGsdeISHZCIiCDBgHQAxZjcPb1JLLGsAbly8gqKS8sr8YPootmtmpJSAEThdUThgNIzsgcdW4tKKuCqTGt8rKGQdLR44FyNVnzIrfvk8ucKFjuWunh7mYS2dyD2nd0Pav1OEuXlfpRUag0CE2l3aSxWpm4tCgjAerFirCAA

💻 Code
type Container = { container: {type: "foo"} | {type: "bar"} | null }

function test(input: Container) {
    if (input.container?.type === 'foo') {
        // works
        acceptsFoo(input.container);
        acceptsFoo({type: "foo"})
        // Does not works
        acceptsFoo(input.container as typeof input.container)
        acceptsFoo({type: "foo"} as typeof input.container)
		/**
Error:
 Argument of type '{ type: "foo"; } | null' is not assignable to parameter of type '{ type: "foo"; }'.
  Type 'null' is not assignable to type '{ type: "foo"; }'.(2345) \
**/
    }
}

function acceptsFoo(input: {type: "foo"}) {}
🙁 Actual behavior

input.container and input.container as typeof input.container are not equivalent.

🙂 Expected behavior

input.container and input.container as typeof input.container should be equivalent.

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 reported narrowing behavior in the linked TypeScript Playground using the provided Container and test function. Start by tracing the type-checker handling of optional property narrowing and typeof assertions; done means input.container and input.container as typeof input.container are treated equivalently without the nullability error.

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.