-
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
Have instances of a generic function #3057
Comments
You can just do: var pushNumber: (i: number, list: number[]) => number[] = pushType; |
Note there's no need to explicitly specify the generic type argument here. function pushType<T>(item: T, list: T[]): T[]{
list.push(item);
return list;
}
pushType(12, [3, 4, 5]); // ok
pushType(1, [4, 5]); // ok
pushType(1, ['']); // error |
Thanks danquirk. No need to explicit specify in that case, I agree. CyrusNajmabadi's comment looks a solution for now, thanks. But I feel my my suggesion more elegant. Do you think is it against any language design or can it be a valid suggestion to implement later? |
You might also be interested in #1616 The problem right now is that the system is not designed in such a way that you can instantiate a generic with a particular type and then 'finish' using it later (ie provide arguments). Certainly people are accustomed to doing something like what you are proposing in certain other languages with different implementations of generics. Given that there are a couple good workarounds (Cyrus' as well as defining a separate function constrained specifically to number which then forwards the call to a more generic version) we would likely need some more compelling use cases to consider complicating the type system like this. |
Can I have an instance of a generic function?
For example I have a function like this:
If I would like to use with number parameter in multiple places, I have to do this:
Can I have an instance of this function for numbers instead of?
Something like this:
var pushNumber = pushType<number>;
is now synax error and compiles tovar pushNumber = pushType();
It would be nice I guess to compile it to
var pushNumber = pushType;
The text was updated successfully, but these errors were encountered: