angulartypescriptundefined

How to make sure that (input) class properties are not undefined?


When I work with Angular and TypeScript, I try to write my code as precise and strict as possible. Reviewing some older code, I came across snippets like this:

export class UserComponent {

    @Input() user: User;

    getName(): string {
        return this.user.firstname + " " + this.user.lastname;
    }

}

Somewhere, this component is used as follows:

<user-component [user]="u"></user-component>

Obviously, such component is meant to display a user and the whole GUI depends on the user instance (value).

The compiler does not complain about this definition, even though the property user could be undefined. However, if another developer forgets to pass the input property user to this component, there will be an error in runtime: Trying to access firstname of undefined.

How do you work around this problem? Personally, I would prefer if the compiler threw an error if a property was not defined in the custructor. Or is there a way to "force" an input property, so that the compiler/Angular CLI will fail if it is not given when the component is used?

Until now, I only see the following options:

1) Define the user property as @Input() user: User | undefined. Then, we have to write a cumbersome if/else in every method that uses the user property.

2) Define @Input() user: User = new User(). But then, I still have to check somehow if we have a valid user instance in many uses.


Solution

  • One trick that could work for you is to define component with all of its required fields in selector. In your case it would be

    @Component({
      selector: 'user-component[user][anotherRequiredField]'
    })