Skip to content

Store the result of a type guard into a const but keep its type guard nature. #35603

Closed
@abidingotter

Description

@abidingotter

Search Terms

type guard store result const

Suggestion

Store the result of a type guard into a const but keep its "type guardiness".

Use Cases

Suppose I have some code containing a type guard:

    public MyFunc($elem: JQuery | string): void {
        if (!(typeof $elem === 'string')) {
            // compiles ok
    	    let $f = $elem.parents('form').first();
        }
    }

Here Typescript knows the $elem is not a string, so it must be a JQuery element, and the compiler is happy.

But say I want to store the result into a const (perhaps for readability and re-use of the expression)

    public MyFunc2($elem: JQuery | string): void {
        const elemIsString = (typeof $elem === 'string');
    
        if (!elemIsString) {
            // fails to compile, $elem is still "JQuery | string" here
            let $f = $elem.parents('form').first();
        }
    }

Is such a thing possible without writing a type guard function? It seems like it could be possible if the result of (typeof $elem === 'string') is not boolean, but instead is of type $elem is string type guard (but is simply emitted as a JavaScript boolean)

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions