Currently learning TypeScript. I have a class:
class ComicBookCharacter {
protected secretIdentity?: string;
alias: string;
health: number;
strength: number;
constructor({ alias, health, strength, secretIdentity }) {
this.alias = alias;
this.health = health;
this.strength = strength;
this.secretIdentity = secretIdentity;
}
}
class SuperHero extends ComicBookCharacter {
getIdentity() {
console.log(`${this.alias} secret name is ${this.secretIdentity}`)
}
}
const superman = new ComicBookCharacter({
alias: 'Superman',
health: 300,
strength: 60,
secretIdentity: undefined,
});
I'm wondering if I have to pass undefined when creating an instance of a class if I made one of the properties optional (like the secretIdentity here);
Removing secretIdentity: undefined gets me a compiler error.
Edit:
After the solution that Shift 'N Tab gave below, I did some more research and you can also specify the constructor like this:
constructor(fields: Partial<ComicBookCharacter> & {
mothersName?: string,
secretIdentity?: string,
}) {
Object.assign(this, fields);
}
And as Shift 'N Tab wrote in the comment below, do not forget to add "strictPropertyInitialization": true in tsconfig file