-
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
Make a method of a generic interface A<T> available only if T is of a certain type #6529
Comments
You could make a subclass of interface LodashFunctionWrapper<T> extends LodashWrapper<T> {
memoize(): LodashFunctionWrapper<T>;
} and add an overload whose parameter is constrained to functions interface Lodash {
<T extends Function>(x: T): LodashFunctionWrapper<T>;
} This is already done to some extent in DefinitelyTyped's declaration file for lodash. By the way, while I can help out with this now, in the future you should really post questions like this to StackOverflow or our Gitter room. Hope that helps! |
I posted on SO, but didn't get an answer. And Lodash is just for example. My question is about a specific language feature, that's why I decided that it's okay to write here. |
And we can get |
In the extreme, this feature could allow overloads like these: interface Foo<T> {
bar(): string if T extends Function;
bar(): number; // otherwise
} |
Turns out there is already an issue for this: #1290. |
Let's look at the library Lodash for the example. Values of any type can be wrapped in
_
:However, not all the methods of the wrapper make sense for any type of the wrapped value. For example, calling
_(z),memoize()
makes sense only ifz
is a function. So let's try to create a type definition for this situation:AFAIK for now it's not possible to write such a constraint for
memoize
that a call to it will type-check only whenT
is a function. Is it going to be possible in the future versions? Is there already an issue for this?The text was updated successfully, but these errors were encountered: