Reputation: 145
I have a question about inheritance and types for instance variables in typescript.
Let's imagine I have a simple class as follows:
class Person {
instanceVariable: Object;
age: Number;
constructor(instanceVariable: Object, age: Number) {
this.instanceVariable = instanceVariable;
this.age = age;
}
};
let alice = new Person({}, 50); //This will work
let sarah = new Person({}, "fifty"); //Typescript will complain here..
Typescript does what you'd expect it to here. It will complain when you try to create sarah :). But now let's imagine that you have another class that extends this, and you want to make sure this class still has the instance variable but overrides the type.
//Create a simple class that extends and overrides the type
class Student extends Person {
instanceVariable: String
}
let bvk = new Student("test", 50); //This should work
let katie = new Student(50, 50); //This shouldn't work
This unfortunately doesn't really work as expected though. Typescript complains: "Property 'instanceVariable' has no initializer and is not definitely assigned in the constructor."
If you try to add the constructor, I'm confused about how to make it work, because I want to basically call "super" to set the data. This doesn't work either though, typescript has the same complaint!
class Student extends Person {
instanceVariable: String;
constructor(instanceVariable: String, age: Number){
super(instanceVariable, age)
}
}
Anyway, I'm probably thinking about this all wrong, but am really curious how to best think about it.
Upvotes: 1
Views: 1162
Reputation: 1182
You could use a generic type for your Person
class:
class Person<T = object> {
instanceVariable: T;
constructor(instanceVariable: T, age: number) {
// ...
}
}
Your Student
then can extend Person
as follows:
class Student extends Person<string> {}
PS: Have a look at the very first point at Do's and Don'ts
Upvotes: 2