Skip to content

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

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

Closed
DanielRosenwasser opened this issue Nov 2, 2016 · 1 comment
Closed

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

DanielRosenwasser opened this issue Nov 2, 2016 · 1 comment
Assignees
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue

Comments

@DanielRosenwasser
Copy link
Member

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;
}
@ahejlsberg
Copy link
Member

Yeah, right now we're a little too strict with the assignment compatibility rules for a keyof T where T is a type parameter. We should allow some type S to be assignable to keyof T if S is assignable to keyof C where C is the constraint of T. Shouldn't be too hard to fix.

@mhegazy mhegazy added the Bug A bug in TypeScript label Nov 3, 2016
@mhegazy mhegazy added this to the TypeScript 2.1.2 milestone Nov 3, 2016
@ahejlsberg ahejlsberg added the Fixed A PR has been merged for this issue label Nov 3, 2016
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue
Projects
None yet
Development

No branches or pull requests

3 participants