Ive been creating my classes like this:
interface ICar {
wheels: number;
model: string;
drive?: () => void;
}
const Car = function(c: ICar) {
this.wheels = c.wheels
this.model = c.model
this.drive = function() {
console.log(this.model) // <-- this doesnt autocomplete when typing `this.`
}
}
A small problem im having is that referencing this
within the class doesn't show autocompletion which is making me make some small mistakes in my much larger classes.
I instead can make a class like this:
interface ICar {
wheels: number;
model: string;
drive: () => void;
}
class Car {
wheels: number;
model: string;
drive: () => void;
constructor(obj: ICar) {
this.wheels = obj.wheels;
this.model = obj.model;
this.drive = function() {
console.log(this.model) // this provides autocompletion and type checking
}
}
}
However, with this, I feel like there is a lot of repetition of code. I dont like how I define the interface ICar
and then i have to essentially repeat the code within the class.
I thought using implements
would fix it eg: class Car implements ICar
but that doesnt work either.
Is there something im missing or am I doing this wrong?
CodePudding user response:
You can actually specify the type of "this" since Typescript 2.0. That should help you get the correct type for the "this" keyword.
Using your example:
interface ICar {
wheels: number;
model: string;
drive?: () => void;
}
const Car = function(this: ICar, c: ICar) {
// Now the type of "this" should be `ICar`
this.wheels = c.wheels
this.model = c.model
this.drive = function() {
console.log(this.model)
}
}
CodePudding user response:
You're editor isn't up to much if it can't spot the class members.
You may want to use an abstract class and extend it, also setting the access scope will auto set the member for you:
abstract class Car {
abstract wheels: number
abstract model: string;
abstract drive(): void;
}
class MyCar extends Car {
constructor(public wheels: number, public model: string) {
super()
}
drive() { }
}