Home > Enterprise >  Define an empty object without optional keys
Define an empty object without optional keys

Time:07-07

I'm trying to define an empty object without defining initial values.

My interface

interface MyDate {
  day: string;
  month: string;
  year: string;
}

My class

export class MyClass implements OnInit {
  date: MyDate = {}; // Error Type '{}' is missing the following properties ...
  buildDate([day, month, year]: Array<string>) {
    this.date = { day, month, year };
  }
}

I can change my interface to set keys as optional:

interface MyDate {
  day?: number;
  month?: number;
  year?: number;
}

Or initiate my object like:

date: MyDate = {
  day: '';
  month: '';
  year: '';
};

But I want to initiate an empty object for beauty purposes ))

CodePudding user response:

You can use the as statement, but this is not good practice.

date: MyDate = {} as MyDate;

CodePudding user response:

Do you just want the properties to be automatically instantiated? Just use a class

class MyDate {
  day = '';
  month = '';
  year = '';
}
date = new MyDate();
buildDate([day, month, year]: Array<string>) {
  this.date = { day, month, year };
}

This way you still follow your object definition - the properties are in fact all strings.

If you define an interface with mandatory properties and then instantiate an empty object, your properties will all be undefined. So you just made the rule that all properties are strings, and proceeded to break that rule. Why bother making the rule in the first place?

  • Related