-
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: Expose collection element's type #3749
Comments
It'd be good to understand what kind of things are showing up in your code other than One alternative approach would be to allow indexing expressions with numeric literals in function fn(x: number[]) {
type elem = typeof x[0];
function foo(y: elem) { }
} |
@RyanCavanaugh I think that allowing indexing expression with numeric literals in would be concise and good solution. |
@RyanCavanaugh While the original example has an array of a known type, the syntax would also be useful in the case where the array type is anonymous, e.g. from a var data = [1, 2, 3].map(v => {
return { raw: v, square: v * v };
});
type DataItem = typeof data[0]; // error |
@ander-nz why? Since TS can derive type for |
@lazutkin Sorry, my post was unclear, so I've updated it. (I meant that the type was unknown to the developer, so |
Approved + accepting PRs: allow |
@RyanCavanaugh looks like this can be closed now? function test(a: number[]) {
return a.map(mapper)
function mapper(v: typeof a[53]) { // or typeof a[number]
return v.toExponential();
}
} |
with indexed types, |
I often needed (and I think others do) to get type of element of collection, especially when dealing with collections of complex type. As a workaround I introduce new dummy variable which is assigned with a value of collection element in order to get its type further through the
typeof
. Here is a sample with simple collection of typenumber[]
A bad things about this approach is need to introduce new dummy variable, and some unclarified declarations
function mapper(v: typeof dummy)
So my proposal is to provide some kind of metadata (which is common for C++ STL, boost) in form of exported type properties like
<...container type...>.ElementType
.Here is not a final syntax, but at least it looks more clear
The text was updated successfully, but these errors were encountered: