Skip to content

Detect the correct conditional return type in class methodsΒ #48926

Closed
@nbouvrette

Description

@nbouvrette

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.

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