microsoft / microsoft/TypeScript
Type narrowing with assertions containing truthy literals
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
TypeScript Version: 4.2.0-dev.20201109
Search Terms:
type narrowing truthy
type narrowing assertion
conditional throw
Code
function test(foo?: number) {
if (!foo) throw new Error();
return foo.toFixed();
}
function testWithLiteralTrue(foo?: number) {
if (!foo && true) throw new Error();
return foo.toFixed();
}
function testWithTruthyLiteral(foo?: number) {
if (!foo && "str") throw new Error();
return foo.toFixed(); // Object is possibly 'undefined'.
}
Expected behavior:
In all three functions typescript would know foo is a number after the assertion.
Actual behavior:
In the last example, testWithTruthyLiteral, typescript complains foo may be undefined. This is the same behavior for all known truthy values except for literal true.
Related Issues:
https://github.com/microsoft/TypeScript/issues/29323
It sounds like from https://github.com/microsoft/TypeScript/issues/29323#issuecomment-454548280 that determining truthiness of expressions could lead to circular dependencies between compiler passes, but that literal true has been special cased. This should be able to be extended to truthy literals without the circular dependency concern.
And for context, like others that have brought up similar issues, this stems from wanting a truthy token that can be used for a minification hook without affecting the types or code execution.
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 linked TypeScript Playground example and compare the three functions using literal true and other truthy literals. Read related issue #29323 and its linked discussion about truthiness analysis and compiler-pass dependencies. Done means truthy literals narrow foo consistently after the conditional throw, with coverage for the reported cases.
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
- 45/100