-
Notifications
You must be signed in to change notification settings - Fork 12.6k
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
Generic parameter type is not enforced #17655
Comments
You problem is that you pass 2 types for TParams and the type Params is assignable to {} so {} is taken to be the type of TParams var v1 : {} = new Params("foo") If the types are incompatible, then the first match from left to right is used: class Base<TParams> {
private params: TParams; //cfr https://github.com/Microsoft/TypeScript/issues/1396
}
class Params {
constructor(public test: string) {
}
}
class Component extends Base<Params> {
}
function testInference<TParams>(component: Base<TParams>, params: TParams) {
}
function testInference2<TParams>(params: TParams, component: Base<TParams>) {
}
var component = new Component();
testInference(component, { foo:1 }); // Error on foo
testInference2({ foo:1 }, component); // Error on component |
What do you mean I'm "passing" 2 types for TParams"? |
Ha, well what do you know! Changing
To
Works! |
I wanted to get back to this again. |
How does it know the correct value of your generic parameter if you pass 2 different values for it? The first one? Well who says that the first one is the one I want, what if it is the second one. You can't make such an assumption like that. The type inference mechanism tries to solve for a correct type based on the types supplied and the type definition. If it can it goes with that - if not you get an error. Here is a nicer way of writing it class Base<TParams> {
private params: TParams; //cfr https://github.com/Microsoft/TypeScript/issues/1396
}
class Params {
constructor(public test: string) {
}
}
class Component extends Base<Params> {
}
type InferLast<T> = T & {}
function testInference<TParams>(component: Base<TParams>, params: InferLast<TParams>) {
}
function testInference2<TParams>(component: Base<InferLast<TParams>>, params: TParams) {
}
var component = new Component();
testInference(component, { }); // Error on foo
testInference2(component, { foo:1 }); // Error on component |
Hmmmm, ok, thanks for the clarification. |
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed. |
TypeScript Version: 2.4.0
Code
Expected behavior:
The second parameter of the call to the "testInference" function should be coerced to be of type "Params".
Actual behavior:
Any type of variable can be passed.
The text was updated successfully, but these errors were encountered: