Closed
Description
🔎 Search Terms
mapped type, map narrowing, generic mapped type, generic narrowing, generic return
🕗 Version & Regression Information
- This changed between versions 3.3.3333 (where it worked) and 3.5.1 (where I see the same errors as on the most recent TS version) based on the playground
⏯ Playground Link
💻 Code
enum SomeTypes {
a,
b,
c
}
type TypeToValueMap = {
[SomeTypes.a]: number,
[SomeTypes.b]: boolean,
[SomeTypes.c]: string
}
const parseValue = <T extends SomeTypes>(value: string, type: T): TypeToValueMap[T] => {
if (type === SomeTypes.a) {
return Number(value);
}
if (type === SomeTypes.b) {
return Boolean(value);
}
if (type === SomeTypes.c) {
return value;
}
throw new Error('Invalid type');
}
console.log(
parseValue('1', SomeTypes.a),
parseValue('1', SomeTypes.b),
parseValue('1', SomeTypes.c)
)
🙁 Actual behavior
All return statements in the parseValue
function result in an error that looks something like:
Type 'number' is not assignable to type 'TypeToValueMap[T]'.
Type 'number' is not assignable to type 'never'.(2322)
This is incorrect because there is no value of T (which must be a member of SomeTypes) that has no mapping into TypeToValueMap, which means that there is no case where narrowing the type should result in never
in TypeToValueMap[T].
🙂 Expected behavior
The code as written should have no errors because I am narrowing type
to a specific value in SomeTypes
, which should provide the TS compiler enough info to map into TypeToValueMap[T]
.
Additional information about the issue
No response
Activity
MartinJohns commentedon Oct 3, 2024
Duplicate of #43922.
ArcticZeroo commentedon Oct 3, 2024
Ah, looks like it is, thanks. Followed that to the original issue: #33014 . Looks like it is potentially desired but not currently planned, and that thread has some workarounds.
Will close this one.