Skip to content

'keyof' doesn't seem to work correctly with this-types #12011

@DanielRosenwasser

Description

@DanielRosenwasser

Neither of the following examples work:

Inherited get & set methods from a root object:

class RootObject {
    get<K extends keyof this>(prop: K) {
        return this[prop];
    }

    set<K extends keyof this>(prop: K, value: this[K]) {
        this[prop] = value;
    }
}

class Person extends RootObject {
    parts: number;

    constructor(parts: number) {
        super();

        this.set("parts", parts);
        console.log(this.get("parts"));
    }
}

Free-standing get & set functions:

class Person {
    parts: number;

    constructor(parts: number) {
        set(this, "parts", parts);
        console.log(get(this, "parts"));
    }
}

function get<T, K extends keyof T>(obj: T, prop: K) {
    return obj[prop];
}

function set<T, K extends keyof T>(obj: T, prop: K, value: T[K]) {
    obj[prop] = value;
}

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions