After upgrading TypeScript, Angular controller registration now fails to compile

后端 未结 3 622
夕颜
夕颜 2021-02-01 02:10

We were using TypeScript 2.2. After upgrading to 2.4, we now get this on compilation:

error TS2345: Argument of type \'typeof TopMenuController\' is not

3条回答
  •  梦谈多话
    2021-02-01 02:34

    Since all of the properties of IController are optional, I believe the errors you are seeing are a result of the new checking for "Weak Types" in TypeScript 2.4. Check this link from Microsoft for details. Also check this related Github issue.

    Some relevant quotes from Microsoft:

    In TypeScript 2.4, we’re adding a similar check for what we call weak types. Any type that contains only optional properties is considered a weak type since it provides few restrictions on what can be assigned to it.

    ...

    In TypeScript 2.4, it’s now an error to assign anything to a weak type when there’s no overlap in properties.

    ...

    You can think of this as TypeScript “toughening up” the weak guarantees of these types to catch what would otherwise be silent bugs.

    Since this is a breaking change, you may need to know about the workarounds which are the same as those for strict object literal checks:

    1. Declare the properties if they really do exist.
    2. Add an index signature to the weak type (i.e. [propName: string]: {}).
    3. Use a type assertion (i.e. opts as Options).

    Edit: Based on this information, a simple solution would then be to implement one of the methods defined in IController. For example, as mentioned by @Amy in the comments, you could just define an empty $onInit method in your controller.

    Edit: For the sake of completeness, here's the full code:

    export class TopMenuController implements angular.IController {
      static $inject = ["$templateCache", "Restangular"];
    
      $onInit() { }
    
      constructor(
          private readonly $templateCache: angular.ITemplateCacheService,
          private readonly restangular: Restangular.IElement) {
      }
    }
    

提交回复
热议问题