Search code examples
angulartypescriptprettier

Prettier removes types


I have no idea why, Im in an Angular app and when I press format document my types get removed.

# Before:
export class AppComponent {
  title:string = 'angular-todolist';
  name:string = 'Michael';
  someInteger:number = 10;
}
# After:
export class AppComponent {
  title = 'angular-todolist';
  name = 'Michael';
  someInteger = 10;
}

Any suggestions as to what might that be?


Solution

  • By default, prettier-tslint is installed with Prettier, and will format according to your tslint.json configuration, automatically fixing minor linter errors.

    The linting rules generated by the Angular CLI have a rule stating that implicitly typed variables don't need explicit typing. Specifically, this is the no-inferrable-types rule in your tslint.json.

    If you weren't assigning the variables inline, their types wouldn't be removed, e.g:

    export class AppComponent {
      name: string;
    
      constructor() {
        this.name = 'Name';
      }
    }
    

    Formatting the above would keep the explicit typing.

    Since the default linting rules are the 'Angular way', I don't think there's a problem leaving it as-is; if a variable is immediately assigned as a string, it's type is obviously a string.

    However, if you wanted to change the Prettier formatting behavior, just change the no-inferrable-types entry in tslint.json to false. If you don't want to change linting rules, you should also be able to disable it in your Prettier workspace config, but your linter will still show an error for the inferrable type.