Skip to content

Polymorphic this[K] inside a class #41495

Closed
@falahati

Description

@falahati

Essentially it seems that the typescript can not resolve the type of a property when it is trying to do a [K in keyof T]: T[K] operation. I don't know the name of this. lookup? in any case, T[K] for T = this is always this[K] and is never resolved further inside of the class. It works great when used from the outside of the class.

TypeScript Version: 4.1.0-dev.20201101

Search Terms: "Polymorphic this" "this generic"

Code
Consider the following code:

type NonFunctionPropertyNames<T> = {
    // tslint:disable-next-line:ban-types
    [K in keyof T]: T[K] extends Function ? never : K;
}[keyof T];

class B {
    public test: number = 0;

    public bar() {
        var isThis = this.clone();
        isThis.test = 2; // WORKS, since `this` is resolved to `B`

        this.change({ test: 10 }); // ERROR, can't assign number to type `this["test"]`
        this.onChange(["test"]); // ERROR, can't validate "test" as a valid property name
    }
    
    public change(map: Partial<this>) {
        // do something
    }

    public onChange(fields: Array<NonFunctionPropertyNames<this>>) {
        // do something
    }

    public clone(): this {
        return this;
    }
}

const b = new B();
b.change({ test: 10 }); // works!!
b.onChange(["test"]); // works!!

Expected behavior:
For it to work regardless of the code being inside the class or outside of it.

Actual behavior:
See code.

Playground Link: typescriptlang.org with inheritance, my actual problem

Related Issues: This issue might have something to do with #39204 or #22934.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions