-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Unexpected intersection inferred from indexed type #35695
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
Comments
Not really unexpected. Inside the function To get this to work you would need some kind of correlated types such as @jcalz proposes here. |
@dragomirtitian Thanks for your detailed explanation. I know the inner logic now but my question is can the inferred type of |
Or, in other words, can we get actual typings for type parameters from indexed types (or inferences, however an index signature parameter type cannot be a union type)? |
@shigma I don't think there is any way to get the implementation types to work out except for a type assertion or using a separate implementation signature: function myFunc<K extends keyof DataTypes>(data: Data, key: K, value: DataTypes[K]): void {
(data[key] as (value: DataTypes[K]) => void)(value);
} |
This is a correct error; a legal call to declare const data: Data;
declare const ab: "a" | "b";
myFunc(data, ab, ""); which corrupts There isn't a sound way to write the function signature, thus no way to correctly implement the body. You can use a type assertion if you pinky-swear to only call it with unit keys. |
Thanks. I will close this issue. |
TypeScript Version: 3.7.2
Search Terms: type alias index signature intersection TS2345
Expected behavior: pass the type checks
Actual behavior: fail with a TS2345 error
Related Issues: #31445, #35613
Note: Although #35613 is marked as duplicated, I think a different approach than #31445 can be used to address this issue. Actually
data[key]
can be inferred as(value: DataTypes[K]) => void
, which solves the problem.Code
Output
Compiler Options
Playground Link: Provided
The text was updated successfully, but these errors were encountered: