-
Notifications
You must be signed in to change notification settings - Fork 12.5k
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
Confusion with generics and functions #14824
Comments
A workaround would be
which gives the correct error |
Yep, that workaround is perfect. Thank you! Still curious about the original code though. |
Inference for const fn2 = <T>(inner: (args: T) => void, args: T) => { }
fn2((args: { a: 1 }) => { }, { a: '' }) // no error..? |
Logged #14829 which is tangentially related (but wouldn't actually solve this) |
Thanks, @RyanCavanaugh. I still don't understand why T doesn't infer to be the more specific of the two types, as it appears to do in |
Inference works by the following process (greatly simplified):
The A more demonstrative example is this, where we assign to const fn1 = <T>(a: T, b: T) => { }
const j = { a: 1 };
const k = {};
// T: { }
fn1(j, k); Note that it'd be wrong to pick the most specific type among the candidates during inference - you wouldn't want |
Thanks for the great explanations as always, @RyanCavanaugh. The thing I'm not understanding is it seems rather subjective whether you'd choose the most specific type in the example you gave. For example, if |
That's not at all obviously an error? var zoo = new Zoo();
var dog = new Dog('spot');
zoo.add(dog);
zoo.add(new Cat('fluffy'));
var a = zoo.getAnimalByName('spot'); // a: Animal
assertEqual(a, dog); |
Here's some code. The first one has two arguments, both of which are type T. The type catcher catches that type T is different.
Now, the first T is inferred from the arguments of a passed function, and the type checker does not catch that T is different.
What's going on here?
More importantly, I would really like to be able to say the type of the 2nd argument is the arguments to the first. How can I say that in a way that catches missing properties?
The text was updated successfully, but these errors were encountered: