The super call must supply all parameters for base class. The constructor is not inherited. Commented out artist because I guess it is not needed when doing like this.
class StreetArtist extends Artist {
constructor(
name: string,
age: number,
style: string,
location: string,
public medium: string,
public famous: boolean,
public arrested: boolean,
/*public art: Artist*/
){
super(name, age, style, location);
console.log(`instantiated ${this.name}. Are they famous? ${famous}. Are they locked up? ${arrested}`);
}
}
Or if you intended the art parameter to populate base properties, but in that case I guess there isn't really a need for using public on art parameter as the properties would be inherited and it would only store duplicate data.
class StreetArtist extends Artist {
constructor(
public medium: string,
public famous: boolean,
public arrested: boolean,
/*public */art: Artist
){
super(art.name, art.age, art.style, art.location);
console.log(`instantiated ${this.name}. Are they famous? ${famous}. Are they locked up? ${arrested}`);
}
}
Answer from mollwe on Stack OverflowVideos
Another solution I eventually came up with, in addition to the ones provided by @iberbeu and @Nypan, is to add and intermediary initProps() method right before the call to scream():
class Person
{
public firstName: string;
constructor(firstName: string, props?: any)
{
this.firstName = firstName;
this.initProps(props);
this.scream();
}
protected initProps(props: any): void
{
}
protected scream(): void
{
console.log(this.firstName);
}
}
class Employee extends Person
{
public lastName: string;
constructor(firstName: string, lastName: string)
{
super(firstName, {lastName});
}
protected initProps(props: any): void
{
this.lastName = props.lastName;
}
protected scream(): void
{
console.log(this.firstName + ' ' + this.lastName);
}
}
Although I think both made a strong point and I should actually be using a factory pattern instead..
Am I doing a dumb thing here?
Yes you are. As iberbeu said in his comment a constructor should never do anything that does not have to do with constructing the object. It is a case of bad practice that can lead to all sorts of unexpected behaviour.
Are there better ways to arrange my code so I don't need to do this?
Using the solution you provided in your C option is the way to go here.
Is there some way to work around this error?
It depends on what you actually want to do. The normal way of doing things is illustrated by yourself in your C option. If the problem you are having is related to actually instantiating complex objects you might want to look in to builder/factory patterns. But if you actually want the constructors to do something you are simply doing it wrong; constructors are not ment to perform actions, they are there to construct objects and nothing else.