Skip to content

Assert functions do not constraint type when they are guarded by a truthy expression. #37295

@mhevery

Description

@mhevery

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

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions