microsoft / microsoft/TypeScript
Type narrowing on object properties lost in async IIFE
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
TypeScript Version: 3.4.0-dev.20190327
Search Terms:
narrowing iife control flow
Code
declare const x: string | undefined;
declare const y: { z: string | undefined };
function needsString(it: string) { return it; }
function a() {
if (!x) {
throw new Error("Missing x");
}
const res1 = (() => needsString(x))(); // all good, per #8849
const res2 = (async () => needsString(x))(); // ditto
if (!y.z) {
throw new Error("Missing z.")
}
const res3 = (() => needsString(y.z))(); // still good
const res4 = (async () => needsString(y.z))(); // now things blow up
}
Expected behavior:
The call to needsString in the expression for res4 succeeds, like the one in res2 and res3. Even though the function is async, the code in it -- at least that's before an await -- runs immediately, I believe, and so should be subject to the narrowing (esp. given that res2 works).
Actual behavior:
Error for needsString(y.z): Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
Related Issues:
https://github.com/Microsoft/TypeScript/pull/8849, which I think was supposed to fix IIFE issues like this, but appears to have missed a case (or I'm missing something).
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
Reproduce the example from the issue in the linked TypeScript Playground using the reported 3.4.0-dev version, comparing the x and y.z narrowing cases around the async IIFE. Trace the compiler's control-flow narrowing for object properties and add coverage so the res4 call accepts y.z as a string without changing the existing res2 and res3 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
- 45/100