Answer a Question
Sign In

Explicitly Declare Types But Infer Where Possible

Wednesday, October 23, 2019

It is best to explicitly declare the types of your variables, function arguments and function return types. Where applicable, do allow the TypeScript compiler to infer types where the declaration and the definition of the variable occurs simultaneously.

Instructions

  • Do:

    specify generic types.

  • Do:

    specify the return type of methods.

  • Do:

    specify the type when the TypeScript compiler cannot infer it.

  • Avoid:

    the use of any, either declare or inferred.

Rules

Avoid

Avoid the use of any

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
@Component({
  templateUrl: "./resports.component.html",
  styleUrls: ["./resorts.component.scss"]
})
export class ResortsComponent implements OnInit {
  /** The fetched ski resorts. */ 
  resorts: Observable<any>;

  /** The authenticated user. */ 
  user: any;

  constructor(private readonly resortService: ResortService) {}

  ngOnInit() {
    this.resorts = this.resortService.loadAll();
  }
}

Do

Specify property types

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { Resort, User } from '@app-core/models';

@Component({
  templateUrl: "./resports.component.html",
  styleUrls: ["./resorts.component.scss"]
})
export class ResortsComponent implements OnInit {
  /** The fetched ski resorts. */ 
  resorts: Observable<Array<Resort>>;

  /** The authenticated user. */ 
  user: User;

  constructor(private readonly resortService: ResortService) {}

  ngOnInit() {
    this.resorts = this.resortService.loadAll();
  }
}

Infer property types

import { Component } from '@angular/core';
import { Observable } from 'rxjs';
import { Resort, User } from '@app-core/models';

@Component({
  templateUrl: "./resports.component.html",
  styleUrls: ["./resorts.component.scss"]
})
export class ResortsComponent {
  /** The fetched ski resorts. */ 
  resorts = this.resortService.loadAll();

  /** The authenticated user. */ 
  user: User;

  constructor(private readonly resortService: ResortService) {}
}
Brian Love
Brian is a software engineer and Google Developer Expert in Web Technologies and Angular with a passion for learning, writing, speaking, teaching and mentoring. He regularly speaks at conferences and meetups around the country, and co-authored "Why Angular for the Enterprise" for O'Reilly. When not coding, Brian enjoys skiing, hiking, and being in the outdoors. Brian recently launched lookout.dev where you can find best practices and expert advice on topics ranging from TypeScript, Angular, React, Node.js and more.
Google Developers Expert

Whoa 🤚 You need to sign in to join the discussion.

Don't worry, if you start a comment, we'll save it for when you return. 😉