-
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
Proposal: allow type arguments of generic being named #22631
Comments
When would the name |
It's the same with normal function calls: let result = doStuff('foo', true, 3.14, 42); // what do all these mean? The usual solutions are to either (a) place comments labeling each argument, or (b) pass an options object so callers have to specify key/value pairs, which is both extensible and self-documenting. You could take both of these approaches with generics too. For example: // Option A:
interface UserInfo { }
var usersMap: Map</*sessionId:*/ string, /*info:*/ UserInfo>;
// Option B:
interface UserInfo { }
type MyMap<T extends {sessionId: any, info: any}, U = T['sessionId'], V = T['info']> = Map<U, V>;
let usersMap: MyMap<{sessionId: string, info: UserInfo}>; |
You can just do
And then use that type. |
This seems to introduce much more complexity than it produces in value. |
This is super useful when you have a function that takes multiple generic arguments and you only want to assert one. This is a example of what the feature could be like: sandbox |
This proposal has at least two very big advantages:
|
That's a proper JavaScript-like solution. |
TypeScript Version: 2.7.0-dev.201xxxxx
Search Terms: named generic type parameters / arguments
Code
Expected behavior:
No error,
Map<sessionId: string, info: UserInfo>
should be equivalent toMap<string, UserInfo>
.Actual behavior:
Syntax error: Generic type 'Map<K, V>' requires 2 type argument(s).
Playground Link:
https://www.typescriptlang.org/play/#src=interface%20UserInfo%20%7B%20%7D%0D%0Avar%20usersMap%3A%20Map%3CsessionId%3A%20string%2C%20info%3A%20UserInfo%3E%3B
Rationale:
Without a name, it is not often immediately clear what a type argument really mean. Take
Map<string, UserInfo>
as an example, is the first argument asessionId
, auserId
or something else? In contrast,Map<sessionId: string, info: UserInfo>
orMap<sessionId: string, UserInfo>
is very clear.The name of a type argument doesn't affect the actual type, just like the name of argument of a function type.
The text was updated successfully, but these errors were encountered: