В ES6 можете да препращате статични методи чрез this.constructor
:
class MainClass {
static info() {
return "This is some information";
}
constructor() {
this.info = this.constructor.info(); // Allows subclass to define different ".info()" method.
}
}
class ChildClass extends MainClass {
static info() {
return "This information is from the child";
}
constructor() {
super();
}
}
Има ли начин да направите това в TypeScript?Искам да мога да заменя статичния метод на супер класа и да го използвам от подкласа, без да предефинирам препратката в метод на екземпляр. В момента единственият начин, по който знам как да получа достъп до статичен метод в TypeScript, използва името на класа.
MainClass.info();
Но ако го направя, подкласът ще продължи да използва MainClass.info();
вместо да е собствено .info()
метод.
Отговори:
2 за отговор № 1Вижте този код на машинопис:
class MainClass {
static info() {
return "This is some information";
}
info: string;
constructor() {
this.info = (this.constructor as any).info(); // Allows subclass to define different ".info()" method.
}
}
class ChildClass extends MainClass {
static info() {
return "This information is from the child";
}
constructor() {
super();
}
}
Ако целта на компилацията е ES6, тя се компилира, за да подобри кода, който сте дали по-горе, и работи добре. Също така работи добре, ако е компилиран до ES5.
Обърнете внимание, че използвах a as any
хак, за да позволите повикване .info()
на constructor
функция.
Като алтернатива можете да замените настройката на this.info
във всеки детски клас. По този начин няма да имате нужда от хак.
2 за отговор № 2
Какво ще кажете за това:
interface MainClassConstructor {
new (): MainClass;
info(): string;
}
class MainClass {
static info() {
return "This is some information";
}
private info: string;
constructor() {
this.info = (this.constructor as MainClassConstructor).info(); // Allows subclass to define different ".info()" method.
}
}
class ChildClass extends MainClass {
static info() {
return "This information is from the child";
}
constructor() {
super();
}
}
редактиране
Можете също така да използвате typeof MainClass
вместо MainClassConstructor
интерфейс, който добавих:
class MainClass {
static info() {
return "This is some information";
}
private info: string;
constructor() {
this.info = (this.constructor as typeof MainClass).info(); // Allows subclass to define different ".info()" method.
}
}
В допълнение има дискусия / предложение за this.constructor
връщайки правилния тип тук: T.constructor трябва да бъде от тип T.
Друга възможност е да се използва метод за отмяна:
class MainClass {
private info: string;
constructor() {
this.info = this.getInfo();
}
protected getInfo(): string {
return "This is some information";
}
}
class ChildClass extends MainClass {
constructor() {
super();
}
protected getInfo(): string {
return "This information is from the child";
}
}