Closed
Description
TypeScript Version: 3.8.3
Search Terms:: Assert Function
Code
function assertString(actual: any): asserts actual is string {}
function expectString(value: string) { }
let devMode: {} = {};
// This works as expected
const x: string|number = '' as any;
assertString(x);
expectString(x); // x is string!
// This fails
const y: string | number = '' as any;
// Expecting TS to correctly infer that `devMode` is always truthy and
// hence the`assertString` sholud always execute therefore its
// type assertion should hold.
devMode && assertString(y);
expectString(y); // y is string|number hence it fails
Expected behavior:
Assert functions should be assumed to always execute when they are guarded by an expression which is truthy.
Actual behavior:
Any sort of guard expression (even if know to be truthy) prevents the assert function from applying its constraint.
Playground Link:
Playground
Related Issues:
Metadata
Metadata
Assignees
Type
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
ngDevMode
asserts angular/angular#35964refactor(core): Take advantage of 'assert functions' for `ngDevMode` …
refactor(core): Take advantage of 'assert functions' for `ngDevMode` …
refactor(core): Take advantage of 'assert functions' for `ngDevMode` …
RyanCavanaugh commentedon Mar 11, 2020
We don't trust the results of our own truthiness analysis for these situations because there are legitimate situations where a falsy value might inhabit a truthy position. We also believe that code like
x && y
is written becausex
is possibly falsy (otherwise why would you do it...?). It seems like you intend to strip this out later, so I'd recommend just using some other approach.typescript-bot commentedon Mar 14, 2020
This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.
typescript-bot commentedon Mar 17, 2020
This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.