Description
Suggestion
π Search Terms
List of keywords you searched for before creating this issue. Write them down here so that others can find this suggestion more easily and help provide feedback.
conditional type method
β 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
When using a class, calling certain methods and getting a certain return value can have a direct impact on the type of another method, which would avoid boilerplate code.
π Motivating Example
In the example below the method getMatch
will return string | undefined
. We could simply call if (resolver.getMatch() !== undefined)
to get the correct type. But adding methods like hasMatch
that returns a boolean
instead makes the code easier to use and more readable.
const resolver = new Resolver(data);
if (resolver.hasMatch()) {
console.log(`This is the match: ${resolver.getMatch()}`); // <-- Invalid type "string | undefined" of template literal expression.
} else {
console.log('`getMatch` returns `undefined` (no match)');
}
The only workaround is to cast as string
or to replace the hasMatch
method with !== undefined
statements which is more verbose and less friendly to use.
π» Use Cases
There could be many use cases where the return value of certain methods could dynamically infer the return type of other methods. The main goal would be to remove boilerplate code, especially when in strict
mode.