Skip to content
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

Static this #8877

Closed
felixfbecker opened this issue May 28, 2016 · 1 comment
Closed

Static this #8877

felixfbecker opened this issue May 28, 2016 · 1 comment

Comments

@felixfbecker
Copy link
Contributor

felixfbecker commented May 28, 2016

Consider this implmentation of a ORM-like Model class:

class Model {
    public static tableName: string;
    public static findById(id: number): this { // error: a this type is only available in a non-static member of a class or interface 
        const rows = db.query(`SELECT * FROM ${this.tableName} WHERE id = ?`, [id]);
        const instance = new this();
        for (const column of rows[0]) {
            instance[column] = rows[0][column];
        }
        return instance;        
    }
}

class User extends Model {
    public static tableName = 'users';
    public username: string;    
}

const user = User.findById(1); // user instanceof User

Currently, this is not possible, because TypeScript does not allow this in static members. There is no reason for this limitation: this inside a static method is simply the class in JavaScript (aka typeof Model or typeof User, depending on what class this is called on).

@yortus
Copy link
Contributor

yortus commented May 29, 2016

Duplicate/related: #5863

@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
None yet
Projects
None yet
Development

No branches or pull requests

2 participants