Skip to content

TypeScript Error in Function Return Types #55334

Closed as not planned
Closed as not planned
@GhomKrosmonaute

Description

@GhomKrosmonaute

🔎 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions