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.