Skip to content

Allow parenthesis in type guards #32130

Closed
@Haringat

Description

@Haringat

Search Terms

type guard parenthesis

Suggestion

I would like to be able to put the asserting part of a type guard function in parenthesis to be able to further work with it.

Use Cases

I have two use cases in mind right now: strong-typed assertions and predicate inversion. However, there may be more that I currently don't think of.

Examples

Strong typed assertions

This would enable code like this:

function assertString(it: unknown): (it is string) extends true ? void : never {
    if (typeof it !== string) {
        throw new Error("not string")
    }
}

This would make the following code possible:

function doSomethingWithStrings(it: unknown) {
    assertString(it);
    return it.startsWith("foo") // it must be a string now
}

It would also allow better detection of dead code/bugs:

function doSomething(it: number) {
    assertString(it);
    // unreachable code

Predicate inversion

function not<T>(predicate: (it: unknown) => it is T): (it: unknown) =>  (it is T) extends true ? false : true {
    return (it: unknown): (it is T) extends true ? false : true => !predicate(it);
}

Using a few more functional predicates we could do something like this:

const isNotNullOrUndefined = not(or(isUndefined, isNull));

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