Skip to content

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

Closed
@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:

Activity

RyanCavanaugh

RyanCavanaugh commented on Mar 11, 2020

@RyanCavanaugh
Member

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 because x 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

typescript-bot commented on Mar 14, 2020

@typescript-bot
Collaborator

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

typescript-bot commented on Mar 17, 2020

@typescript-bot
Collaborator

This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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

        Participants

        @mhevery@RyanCavanaugh@typescript-bot

        Issue actions

          Assert functions do not constraint type when they are guarded by a truthy expression. · Issue #37295 · microsoft/TypeScript