Skip to content

Add support for type guarding to if statementsΒ #53201

Open

Description

Suggestion

πŸ” Search Terms

type guard guarding assertion

βœ… Viability 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, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

This proposal introduces a new feature that would allow developers to use type guard statements with if-statements rather than only with functions. This feature would provide a more concise and expressive syntax for type guards, making code easier to read and maintain.

πŸ“ƒ Motivating Example

With the proposed feature, developers could use the is keyword directly within an if-statement to perform a type guard. For example…

Before β€” requires separate function for type guarding

function isIterable<T>(obj: Iterable<T> | ArrayLike<T>): obj is Iterable<T> {
  return typeof (obj as Iterable<T>)[Symbol.iterator] === 'function';
}

function iterateOver<T>(obj: Iterable<T> | ArrayLike<T>, expose: Function) {
  if (isIterable(obj)) {
    // some logic here
  } else {
    // some logic here
  }
}

After β€” can handle type guarding inline via if statement

function iterateOver<T>(obj: Iterable<T> | ArrayLike<T>, expose: Function) {
  const isIterable = typeof (obj as Iterable<T>)[Symbol.iterator] === 'function';
  if (isIterable): obj is Iterable<T> {
    // some logic here
  } else {
    // some logic here
  }
}

** this could just as easily be rewritten to get rid of the isIterable placeholder altogether, like this:

function iterateOver<T>(obj: Iterable<T> | ArrayLike<T>, expose: Function) {
  if (typeof (obj as Iterable<T>)[Symbol.iterator] === 'function'): obj is Iterable<T> {
    // some logic here
  } else {
    // some logic here
  }
}

πŸ’» Use Cases

Currently, if developers want to use a type guard to narrow down the type of a value within an if statement, they need to define a separate function (AFAIK) that returns a boolean value indicating whether the value is of a certain type. This approach can be cumbersome and can lead to code that is harder to read and understand.

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

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions