Microsoft/TypeScript

Report better errors on return expressions for immediately-assigned functions

Open

#42,161 创建于 2020年12月31日

在 GitHub 查看
 (6 评论) (2 反应) (0 负责人)TypeScript (6,726 fork)batch import
Domain: Error MessagesEffort: ModerateExperience EnhancementExperimentation NeededHelp WantedSuggestion

仓库指标

Star
 (48,455 star)
PR 合并指标
 (平均合并 6天 17小时) (30 天内合并 9 个 PR)

描述

Suggestion

🔍 Search Terms

return type label:"Domain: Error Messages"

✅ 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

Error reporting for mismatches between a functions return type and what is being returned by a particular return statement should be consistently reported a the location of the offending return.

📃 Motivating Example

TypeScript Playground

type Foo = (input: string) => number;

const foo: Foo = (input) => {
  switch (input) {
    case "1":
      return 1;
    case "2":
      return "2";
    default:
      return Infinity;
  }
}

The following error is reported on the declaration of foo.

const foo: Foo
Type '(input: string) => number | "2"' is not assignable to type 'Foo'.
  Type 'number | "2"' is not assignable to type 'number'.
    Type 'string' is not assignable to type 'number'.(2322)
const bar = (input: string): number => {
  switch (input) {
    case "1":
      return 1;
    case "2":
      return "2";
    default:
      return Infinity;
  }
}

The following error is reported on return "2":

Type 'string' is not assignable to type 'number'.(2322)

💻 Use Cases

In the second example it's much easier to see where the problem is. In larger functions for more `returns it can be even hard to pin down which one is causing the issue. These two examples are very similar and I would expect the same error to be reported for each.

贡献者指南