microsoft / microsoft/TypeScript

TypeScript doesn't narrow out `undefined` after constructor call when callee is `any`

Open
#27,993 11 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Domain: check: Control Flow Needs Proposal Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript doesn't seem to narrow the type of a variable correctly in cases where the constructor being called is typed as any. If the type of a variable includes undefined in its type signature, it's not narrowed out after a constructor call even though by definition (I think--correct me if I'm wrong) new fn() must always evaluate to an object if it doesn't throw first.

TypeScript Version: 3.1.3

Search Terms: constructor narrow

Code

let x: { [x: string]: any } | undefined;
x = new (Object as any)();
// AFAIK `x` can't possibly be undefined after this point
console.log(x.foo);  // error: Object is possibly 'undefined'.

Expected behavior:
No error.

Actual behavior:
Compile-time error: Object is possibly 'undefined'.

Playground Link:
http://www.typescriptlang.org/play/#src=let%20x%3A%20%7B%20%5Bx%3A%20string%5D%3A%20any%20%7D%20%7C%20undefined%3B%0D%0Ax%20%3D%20new%20(Object%20as%20any)()%3B%0D%0Aconsole.log(x.foo)%3B%0D%0A

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 with the TypeScript Playground repro and the new (Object as any)() assignment shown in the issue. Trace how control-flow narrowing handles constructor calls whose callee is any, then verify that the example no longer reports Object is possibly 'undefined' without changing unrelated narrowing behavior.

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
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.