'Is there a way in typescript to declare type of this when defining an literal object
My case is that a javascript lib uses mixin method to create an object. Let's say it's a Car. In js, codes like
function Car( yourInjectObject ){
Mixin(this, yourInjectObject)
}
Car.prototype.Run = function (){ ... }
Now in car.d.ts
class Car{
Run(){ ... }
}
Now if I want to write my injectObject, I should always declare an interface
interface IMyInject extends Car{
someVar:number
Func1(){}
Func2(){}
//Func3(){} // no Func3 declare
}
let injectObject = {
someVar: 0,
Func1(this: IMyInject ){
this.Run() // ok
this.Func2() // ok
this.Func3() // type error, Func3 not declared
},
Func2() { // if I forgot add a this declare
this.Run() // type error
this.Func3() // type error, no declare of
this.Func1() // type error
},
Func3(this: IMyInject ){ //
this.Run() // ok
this.Func1() // ok
this.Func2() // ok
this.Func3() // type error,
},
}
let mycar = new Car(injectObject)
Is it possible to ease the codes, without predeclaring an interface. Suggest:
let myInject = MixIn<Car>{
someVar:1,
Func1(){
this.someVar =2;
this.Run()
this.Func2()
},
Func2(){
this.Run()
this.Func1()
}
}
let myCar = new Car(myInject)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
