I'm having an issue with Typescript where I extend a class and override a property from the super, however the super class property is still read in the constructor when I instantiate the sub class. Please see the below example:
class Person {
public type:string = 'Generic Person';
public constructor() {
console.log(this.type);
}
}
class Clown extends Person {
public type:string = 'Scary Clown';
}
var person = new Person(), // 'Generic Person'
clown = new Clown(); // 'Generic Person'
console.log(person.type); // 'Generic Person'
console.log(clown.type); // 'Scary Clown'
My expected behaviour would be 'Scary Clown' when I instantiate an instance of Clown. Is there another way I can achieve this without passing the values into the constructor itself or having some sort of init method that I fire manually after instantiating?
Thanks in advance :)
Use the Omit utility type to override the type of an interface property, e.g. interface SpecificLocation extends Omit<Location, 'address'> {address: newType} . The Omit utility type constructs a new type by removing the specified keys from the existing type.
When a method is marked with override , TypeScript will always make sure that a method with the same name exists in a the base class. This member cannot have an 'override' modifier because it is not declared in the base class 'SomeComponent'.
In TypeScript, we cannot define multiple constructors like other programming languages because it does not support multiple constructors.
TypeScript supports only single inheritance and multilevel inheritance. It doesn't support multiple and hybrid inheritance.
Property initializers are inserted right at the top of the constructor before the manually entered body of the constructor. So
class Person {
public type:string = 'Generic Person';
public constructor() {
console.log(this.type);
}
}
Becomes
var Person = (function () {
function Person() {
this.type = 'Generic Person';
// NOTE: You want a different value for `type`
console.log(this.type);
}
return Person;
})();
As you can see there is no way to get a different type
in the parent constructor body using a property initializer.
Alternatively don't use type
and rely on built-in constructor
property:
interface Function{name?:string;}
class Person {
public constructor() {
console.log(this.constructor.name);
}
}
class Clown extends Person {
}
var person = new Person(), // 'Person'
clown = new Clown(); // 'Clown'
console.log(person.constructor.name); // 'Person'
console.log(clown.constructor.name); // 'Clown'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With