Skip to content

Proposal: Expose collection element's type #3749

Closed
@lazdmx

Description

@lazdmx

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 type number[]

function test(a: number[]) {
    var dummy = a[0]

    return a.map(mapper)

    function mapper(v: typeof dummy) {
        // some code
    }
}

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

function test(a: number[]) {
    return a.map(mapper)

    function mapper(v: (typeof a).ElementType) {
        // some code
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Effort: ModerateRequires experience with the TypeScript codebase, but feasible. Harder than "Effort: Casual".FixedA PR has been merged for this issueHelp WantedYou can do thisSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions