Skip to content

Narrowing type via Function Assertion loses numeric type #37807

Closed
@eyedean

Description

@eyedean

TypeScript Version: 3.9.0-dev.20200406

Search Terms: assertion, function, narrowing, numeric types

Code

// GOOD EXAMPLE
function f1(x: any): asserts x is number | undefined { }
let v1: number | string | undefined;
f1(v1)
type t1 = typeof v1; // t1 = number | undefined, as excepted

// BUGGY EXAMPLE
function f2(x: any): asserts x is 6 | undefined { }
let v2: number | string | undefined;
f2(v2)
type t2 = typeof v2; // t2 = undefined.  Expected to be 6 | undefined

Expected behavior: t2 must be 6 | undefined.

Actual behavior: t2 is undefined only.

Playground Link: Playground Link

Related Issues: I went through the comments of the popular #32695 by @ahejlsberg and also searched in the existing issues but couldn't find any similar problem being reported in the past.

FWIW, I ran into this trying to write a assertIsInEnumValues for Numeric Enums. (related StackOverflow question: https://stackoverflow.com/a/61058457)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions