I am pondering about the topic of inheritance and types for instance variables in typescript.
Consider a basic class as shown below:
class Person {
instanceVariable: Object;
age: Number;
constructor(instanceVariable: Object, age: Number) {
this.instanceVariable = instanceVariable;
this.age = age;
}
};
let alice = new Person({}, 50); //This will succeed
let sarah = new Person({}, "fifty"); //Typescript will raise an error..
Typescript behaves as expected by throwing an error when attempting to create sarah :). Now, let's contemplate a scenario where another class extends this one, and we need to ensure this class still contains the instance variable but overrides the type.
//Define a simple class that extends and modifies the type
class Student extends Person {
instanceVariable: String
}
let bvk = new Student("test", 50); //This should work
let katie = new Student(50, 50); //This should not work
Regrettably, this approach does not function as expected. Typescript issues a warning: "Property 'instanceVariable' has no initializer and is not definitely assigned in the constructor."
If we attempt to add a constructor, I am uncertain about how to make it function, as I essentially want to invoke "super" to set the data. Nevertheless, this also triggers the same error in typescript!
class Student extends Person {
instanceVariable: String;
constructor(instanceVariable: String, age: Number){
super(instanceVariable, age)
}
}
In any case, I may be approaching this issue incorrectly and am keen to discover the most effective way to address it.