81

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.

specify the return type of methods.

specify the type when the TypeScript compiler cannot infer it.

Avoid

the use of any, either declare or inferred.

Code Examples

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) {}
}

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();
  }
}

Rules

Brian Love

I am a software engineer and Google Developer Expert in Web Technologies and Angular with a passion for learning, writing, speaking, teaching and mentoring. I regularly speaks at conferences and meetups around the country, and co-authored "Why Angular for the Enterprise" for O'Reilly. When not coding, I enjoy skiing, hiking, and being in the outdoors. I started lookout.dev to break down the barriers of learning in public. Learning in public fosters growth - for ourselves and others.

Google Developers Expert

Discussions are healthy ❤️