Closed
Description
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
Labels
No labels