mdmb
mdmb

Reputation: 5283

TypeScript optional in class constructor

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

Upvotes: 2

Views: 2701

Answers (2)

Shift &#39;n Tab
Shift &#39;n Tab

Reputation: 9443

If you wanna make an object argument in the constructor you can do that by Object destructuring approach.

class ComicBookCharacter{
    secretIdentity?: string;
    alias: string = '';
    health: number = 0;
    strength: number = 0;

    constructor(character: { alias: string, health : number, strength : number, secretIdentity?: string }) {
        Object.assign(this, character);
    }

}

Upvotes: 2

Paul
Paul

Reputation: 478

I think you can set secret identity to an empty string in the constructor ( secretIdentity = ‘’ ).

Upvotes: 0

Related Questions