Microsoft/TypeScript

switch (typeof something) isn't seen as exhaustive

Open

#56,786 建立於 2023年12月14日

在 GitHub 查看
 (5 留言) (0 反應) (0 負責人)TypeScript (6,726 fork)batch import
Domain: check: Control FlowHelp WantedPossible Improvement

倉庫指標

Star
 (48,455 star)
PR 合併指標
 (平均合併 6天 17小時) (30 天內合併 9 個 PR)

描述

🔎 Search Terms

  • typeof
  • switch
  • narrow
  • type guard

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about Type Guards

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.3.2#code/GYVwdgxgLglg9mABBAFgUwgawIIBtcA8AKgHwAUAznALZpQoxgDmAXIkQJRtGIDeAUIkQUA7jCipEZKAE8ADmjjBhNOg2Yc+gocgCGFNIgBEYENQBGaAE5GW2oRH2Gj5mE0ZRb9vQePm4cLhoumBeOj7OFDIWgWE6jr5G4AAmaMCMaMlxDk7GoJCwCNkRxnDmAFYYnnbhCZFQVoxMxUJWdCBWSFS09E0A3NoAvvyDQA

💻 Code

function checkAll<T>(something: T): T {
  switch (typeof something) {
    case "number":
    case "bigint":
    case "boolean":
    case "symbol":
    case "undefined":
    case "function":
    case "object":
    case "string":
      return something;
  }
}

🙁 Actual behavior

This emits the TS error: "Function lacks ending return statement and return type does not include 'undefined'.(2366)"

🙂 Expected behavior

No error, since all possible results of typeof are handled.

Additional information about the issue

It seems to only be an issue when the function argument is generic. It works if I switch the return type and parameter types to any, but I'm not sure that's a fair comparison.

貢獻者指南