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?
classsyntax to create a class; the thing about code repetition is just that you don't need to declare your interface at all, the class can be used like an interface because Typescript uses structural types, not nominal types.function()( { ... }withthisinside almost certainly is not what you actually want here.thisdoesn't refer to thethisfrom the class. If you use an arrow function like() => { ... }then you can usethisfrom the outer scope. It's also kind of suspect that your constructor's parameter is something of the same typeICarthat you are (apparently) trying to construct; if you already have an argument of typeICarto pass to the constructor then what do you need to call the constructor for?