Skip to content

generics for "this" type #8740

@pleerock

Description

@pleerock

Need to allow to use generics for "this" type, like this: this<T>

class Collection<T> extends Array<T> {

    map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): this { 
        // this method will return this<T>, but I want to return this<U>
        return new (this.constructor as any)(...super.map(callbackfn, thisArg));
    }

}

example of usage:

new Collection(
    new Model(1, "Mercedes"),
    new Model(2, "BMW"),
    new Model(3, "Ford")
)
    .map(model => model.engine)
    .forEach(engine => engine.serialNumber); // here compiler should see engine.serialNumber

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions