lookout.devlookout.dev
search
Share Knowledge
10

Allow for Type Inferencing Where Appropriate

Tuesday, January 21, 2020

Type inferencing is defined as allowing a compiler to determine the type rather than explicitly defining a type. This can be applied to class properties and variables as well as method and function arguments and return types.

It is important to note that where a compiler cannot infer the type you should attempt to explicitly define the type. A compiler may not be able to infer type in scenarios such as where an unknown or any type has been defined, when a generic type is not specified, or when the type header file or declaration file is not provided to the compiler.

Allowing the compiler to appropriately infer a type is a matter of convenience, brevity of code, and reduction in engineering effort, which can lead to gains in productivity and reduction in costs.

Instructions

checkmark-circle
Do

avoid explicitly defining types when also declaring values of a variable or property in the same line

error-circle
Avoid

type inferencing where explicit types improve readability and maintenance

question-circle
Consider

not explicitly defining types when inferencing is both available and obvious

info-circle
Why

type inferencing leads to brevity of code and convenience

Code Examples

Use type inferencing when declaring a variable value immediately

export class Actions<Props, ActionState> {

  /** Toggle back action */
  back = false;

  toggleBackBtn() {
    this.back = !this.back;
  }

}

Infer method return type where complexity is low and brevity provides clarity

export class UserProfileComponent {

  constructor(private readonly userService: UserService) { }

  getUsers() {
    return this.userService.users$;
  }

}

explicitly declaring the type of a variable when immediately assigned a value

export class Actions<Props, ActionState> {

  /** Toggle back action */
  back: boolean = false;

  toggleBackBtn() {
    this.back = !this.back;
  }

}

defining the return type of a method when inferred

export class UserProfileComponent {

  constructor(private readonly userService: UserService) { }

  getUsers(): Observable<User[]> {
    return this.userService.users$;
  }

}
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

Have a question or comment?