Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeScript Error in Function Return Types #55334

Closed
GhomKrosmonaute opened this issue Aug 11, 2023 · 1 comment
Closed

TypeScript Error in Function Return Types #55334

GhomKrosmonaute opened this issue Aug 11, 2023 · 1 comment

Comments

@GhomKrosmonaute
Copy link

🔎 Search Terms

"Function Return Types", "Type Inference", "Type Error", "keyof", "Type Assignment"

🕗 Version & Regression Information

Environment:

  • TypeScript Version: 5.1.6
  • Node Version: 18.12.1
  • Operating System: Windows 11
  • IDE: WebStorm 2023.2

tsconfig.json:

{
  "compilerOptions": {
    "strict": true,
    "lib": ["ESNext", "dom"],
    "module": "ESNext",
    "target": "ESNext",
    "skipLibCheck": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "resolveJsonModule": true
  }
}

Additional Information:
This issue seems to have emerged after a recent update in the TypeScript version. The code logic appears to be accurate, and the TypeScript configuration in my tsconfig.json file seems appropriately configured. The discrepancy between the expected behavior and the actual TypeScript error suggests a potential bug in TypeScript's latest version or a misconfiguration.

⏯ Playground Link

https://www.typescriptlang.org/play?#code/FAFwngDgpgBAgjAvDAjKSsBCSYCZjACWAdiFAE4BmAhgMZYD2IAFjAN7AwzUBc8nMAEZ9MwAL4FKAV2K0QhBsRhkAziAA8AaRhQAHmWIATFTADWUMA0oxMTZgD4AFObB9NAShF2A2poC67AIqAO6EILSszhbugVxctNQqsABE1Mk8AnEw5FAgUuRKKNwmtIpqmTCGUDRSADYgGVlcOXkFeMUwpcTlXBISoFBqjqnJ7gDcAkA

💻 Code

type A = 1
type B = 2

interface Both {
  a: A
  b: B
}

function test<K extends keyof Both>(key: K): Both[K] {
  switch (key) {
    case "a":
      return 1 as const
    default:
      return 2 as const
  }
}

test("a");

🙁 Actual behavior

Error Messages:
The error messages I'm encountering is:

TS2322: Type  1  is not assignable to type  Both[K] 
Type  number  is not assignable to type  never.

TS2322: Type  2  is not assignable to type  Both[K] 
Type  number  is not assignable to type  never.

🙂 Expected behavior

The function test should compile without any errors, as the return types are correctly inferred and match the expected types defined in the Both interface. The final call to test("a") should yield the expected return type of 1.

@MartinJohns
Copy link
Contributor

Duplicate of #33014.

@GhomKrosmonaute GhomKrosmonaute closed this as not planned Won't fix, can't repro, duplicate, stale Aug 11, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants