我有一个基本模型类,如下所示:
class Base {
abstract public save(): Promise<Base>;
}
我的模型继承自Base,并且必须实现save
方法。例如,
class User extends Base {
public save(): Promise<User> {
// save my user in the database and return a promise like this...
return getDatabaseConnection()
.then((db) => db.insert(...))
.then((res) => this);
}
}
这很好用,并且Typescript在这里的类型没有问题。
但是随着我的发展,我注意到我的模型save
方法非常相似...
class Group extends Base {
public save(): Promise<Group> {
// save my group in the database and return a promise like this...
return getDatabaseConnection()
.then((db) => db.insert(...))
.then((res) => this);
}
}
class OtherModel extends Base {
public save(): Promise<OtherModel> {
// save my other model in the database and return a promise like this...
return getDatabaseConnection()
.then((db) => db.insert(...))
.then((res) => this);
}
}
因此我想到,为了使事情保持干燥,我可以实现一个装饰器,以将save
方法添加到类中。
const save = (table: string,idColumn: string) => {
return function decorator<T extends {new(...args: any[]): {}}>(target: T): T {
return class extends target {
public save = function() {
// save whatever model this is & return it
return getDatabaseConnection()
.then((db) => db.insert(...use the table,idColumn args...))
.then((res) => this);
};
}
};
};
@save('user_table','id')
class User extends Base {}
@save('group_table','id')
class Group extends Base {}
@save('other_table','id')
class OtherModel extends Base {}
它的工作原理很吸引人,只是... Typescript抱怨类声明中缺少抽象方法save
。
我一直在使用@ts-ignore
语句来解决它,但是我想删除它们。
我碰到了this question,它是关于通过装饰器添加到类中的 new 方法的,而且我知道装饰器无意修改接口或协定,但这不是事实。我在这里我正在尝试实现每个接口都存在(并且必须实现)的抽象方法。
如何通过装饰器让Typescript识别出我确实实现了抽象方法?