Description
🔎 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
💻 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
.
Activity
MartinJohns commentedon Aug 11, 2023
Duplicate of #33014.