Skip to content

Static this #8877

Closed
Closed
@felixfbecker

Description

@felixfbecker

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).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions