microsoft / microsoft/TypeScript
TypeScript doesn't narrow out `undefined` after constructor call when callee is `any`
Nobody has claimed this yet.
- 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'.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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