Multiple inheritance
-
There's a class and a design function. It's trying to make a class that's kind of a descendant of both. In fact, the methods from the prototype of the design function are copied into a prototype class-out of the class.
Yeah, I know it's not a full inheritance, but it's enough to do that.
The problem is different. How do you get a typscrypt to take replicated methods?
class First { someMethod() { console.log('someMethod from First'); } }
function Second() {
console.log('Second');
}Second.prototype.doSmth = function () {
console.log('doSmth from Second');
}interface IBoth {
someMethod()
doSmth()
}class Both extends First /* implements IBoth */ {
constructor() {
console.log('constructor of Both');
super();
Second.call(this);
}
}for (let key in Second.prototype) {
Both.prototype[key] = Second.prototype[key];
}
In fact, we need to keep the methods visible to a level further.
class Final extends Both {
doIt() {
this.someMethod();
//this.doSmth(); // Надо заставить видеть метод тут
(this as any as IBoth).doSmth(); // Компилируется, но это ужас
}
}
If the methods are not visible from the very beginning
Both
that's good.That's what I've tried:
When trying to write
class Both extends First implements IBoth {
There's a mistake that I'm not working the interface.
Renamed
Both
Total_Both
and usevar Both = _Both as typeof _Both;
Everything is as logical as it was, because there's no use here.
First
♪Renamed
Both
Total_Both
and usevar Both = _Both as typeof IBoth;
He says he can't find a name.
IBoth
♪
I've had a few more options, but they're completely insane.
What else can we do?Let's try this: http://www.typescriptlang.org/Playground
http://www.typescriptlang.org/Playground#src=class%20First%20%7B%0D%0A%20%20someMethod()%20%7B%0D%0A%20%20%20%20console.log(Start (right panel code) after adding the line:
(new Final).doIt();
Discharge of launch in the rewritten line
this.doSmth();
constructor of Both
Second
someMethod from First
doSmth from Second
doSmth from Second
PS: https://stackoverflow.com/questions/34232656/imitate-multiple-inheritance
-
We don't need an interface, we just need to announce a prototype field with the right type:
doSmth: () => void
She looks like a characteristic, not a method, but it's unscrupulous.
Full code:
class First { someMethod() { console.log('someMethod from First'); } }
function Second() {
console.log('Second');
}Second.prototype.doSmth = function () {
console.log('doSmth from Second');
}class Both extends First {
constructor() {
console.log('constructor of Both');
super();
Second.call(this);
}doSmth: () => void
}for (let key in Second.prototype) {
Both.prototype[key] = Second.prototype[key];
}class Final extends Both {
doIt() {
this.someMethod();
this.doSmth();
//Both.prototype.doSmth(); // ok
//Final.prototype.doSmth(); // ok
}
}
PS: You should've googled not all the variants.
typescript class prototype variable
- I found the right way.