-
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
Suggestion: Improve generics inference with decorators #2686
Comments
My preference is to try to fix type inference in such a way that this sort of manual direction of the system is not required. We talked about this example a bit and think there's actually a pretty simple solution (need to test the full repercussions though). Are there any other examples where you'd need this facility aside from this case where a generic function takes some number of callbacks whose parameter type is a supertype of an inference site that isn't a function type? |
@danquirk This case can indeed be fixed by a different algorithm, since declare function createElement<P>(type: { new(p: P): React.Component<P> }, props: P): ReactElement<P>;
createElement(MyComponent, propsVariable) Here interface Props { foo: boolean }
class MyComponent<Props> extends React.Component<Props> { }
createElement(MyComponent, { }); I think it's hard to fix this example without adding extra type info. |
In fact does not this problem could be easily solved if typescript reintroduced constrain between generics ? declare function createElement<P, U extends P>(type: { new(p: P): React.Component<P> }, props: U): ReactElement<P>;
interface Props { foo: boolean }
class MyComponent<Props> extends React.Component<Props> { }
createElement(MyComponent, { }); // error {} does not extends Props |
I think this can be closed, as #5949 implements the suggestion of @fdecampredon. |
There have been a lot of users who find it strange that this would compile:
Suggestion: use the decorator
@infer
to tell the compiler to infer a generic from that argument.Example:
You can also add
@infer
to multiple arguments, like this:Adding
@infer
to all parameters would have the same behavior as having no@infer
. Adding@infer
is optional, thus not a breaking change.Rules for
@infer
:@infer<T> @infer<U>
(or maybe@infer<T, U>
?)@infer
decorator are inferred using the current behaviorT
that is referenced from an@infer<T>
decorator is resolved using all parameters that are decorated with@infer<T>
of that function.Note that this syntax is currently not supported, as the compiler expects
(
after the generics. An alternative would be to write it as@infer<U>()
, but I think@infer<U>
is cleaner.The text was updated successfully, but these errors were encountered: