assert incorrectly narrows type
See original GitHub issueThis code:
import { assert } from "tsafe";
const x: string | undefined = Math.random() < 0.5 ? undefined : "wtf";
assert(x);
let y: string = x;
console.log(y);
should not compile, but it does. Half the time it will console.log undefined
and half the time will console.log wtf
. Yet the type of y
is supposedly a string.
It’s not obvious why, so to avoid the spoiling the fun the explanation is base64 encoded: QXNzZXJ0IGlzIGRlZmluZWQgd2l0aCBgY29uZGl0aW9uOiBhbnkgPSB0cnVlYCB3aGljaCBjb21waWxlcyB0byAiaWYgY29uZGl0aW9uIGlzIHVuZGVmaW5lZCwgbWFrZSBpdCB0cnVlIiB3aGlsZSB0aGUgdHlwZSBzaWduYXR1cmUgZG9lc24ndCByZWZsZWN0IHRoaXMuIA==
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:8 (8 by maintainers)
Top Results From Across the Web
narrowing types via type guards and assertion functions - 2ality
The problem in this case is that, without narrowing, we can't access property .second of a value whose type is FirstOrSecond .
Read more >FR: assertions that throw could narrow types · Issue #45280
After a type narrowing assertion which throws, the type can be narrowed. This is a common pattern in Closure codebases. function assert<T> ...
Read more >TypeScript: type narrowing: assert not undefined and hence ...
There's a longstanding bug/issue whereby TypeScript does not perform control flow analysis to narrow the type of a property if the property ...
Read more >Documentation - Narrowing - TypeScript
The in operator narrowing JavaScript has an operator for determining if an object has a property with a name: the in operator. TypeScript...
Read more >Type Narrowing in TypeScript - Medium
TypeScript exploits this information and narrows the type of x from unknown to number in the body of if statement. This article will...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
@garronej The example is actually quite relevant.
What do you think the outcome of my example is?
Presumedly you think it will do this:
But it doesn’t. Run it and see ;P It does not throw a runtime exception, even though it narrows the type as if it did.
Hi @husseinhere,
I fixed the code after merging it. The condition deeded to be optional and that was it.