-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Allow narrowing generic type to single element of union type #17713
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
Very difficult to see how this could be enforced. You could equally have written this let runFn= <K extends keyof (typeof index)>(key1: K, key2: K) => {
let i = index[key1]
let arg = i.arg
let fn = index[key2].fn
fn(arg) // Error: compiler doesn't understand that fn and arg will match
}
runFn<'a' | 'b'>('a', 'b'); which is indistinguishable from a type perspective (all expressions used here have the same type as in your example). You could written a different type than |
The suggestion is to perhaps introduce a new syntax to mean |
Using let runFn= <K in keyof (typeof index)>(key1: K, key2: K) => {
let i = index[key1]
let arg = i.arg
let fn = index[key2].fn
fn(arg) // OK here
}
runFn<'a' | 'b'>('a', 'b'); // Error here - K in keyof matches only 'a' or 'b', but not 'a' | 'b' |
+1 to the idea of |
This request hinges on #7294. the main problem here is that regardless of how |
If we had the declarations: interface ArgTypes {
a: string;
b: number;
}
let index: {[K in ArgTypes]: {arg: ArgTypes[K], fn: (arg: ArgTypes[K]) => ArgTypes[K]}} = {
a: {
arg: 'a',
fn: (a: string) => {a.toUpperCase()}
},
b: {
arg: 1,
fn: (b: number) => {b + 1}
}
}
let runFn= <K in keyof (typeof index)>(key1: K, key2: K) => {
let i = index[key1]
let arg = i.arg
let fn = index[key2].fn
fn(arg) // OK here
} then we don't need the case analysis on |
It is a fairly common pattern to create a set of generic components, and then to use the generic component type within the system. Currently, typescript has an issue handling cases where some values of a generic component depend on others.
TypeScript Version: 2.4.0 / nightly (2.5.0-dev.201xxxxx)
2.4
Code
Expected behavior:
No error, since we know that
arg
andfn
are pulled off of the same map entry.Actual behavior:
Error: cannot invoke expression whose type lacks a call signature
The text was updated successfully, but these errors were encountered: