Explicitly declare types but infer where possible
Wednesday, October 23, 2019
Explicitly declare types but infer where possible
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
checkmark-circle
specify generic types.
specify the return type of methods.
specify the type when the TypeScript compiler cannot infer it.
error-circle
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
- tslint: no-any
- tslint: no-unsafe-any
Have a question or comment?