After upgrading TypeScript, Angular controller registration now fails to compile
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:
- Declare the properties if they really do exist.
- Add an index signature to the weak type (i.e. [propName: string]: {}).
- 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) {
}
}
I also faced the same issue which I got resolved by
implementing
IController
add this code before constructor (or anywhere in code this is my preference)
$onInit = () => { };
here is the full code, Hope this will give a clear view
module MyApp {
export class HomeController implements angular.IController {
$onInit = () => { };
user: string;
constructor() {
this.user = "mali";
}
}
angular.module('app').controller('homeController', MyApp.HomeController)
}
Happy Coding