Jakub S Jakub S - 2 months ago 15x
AngularJS Question

How to properly handle AngularJS $inject annotation with Flowtype

I'm trying to use Flowtype in an AngularJS (1.5) project but it complains about the $inject annotation. What is the correct way to handle this?

Flow version 0.30.0

Example code


export default class LinksController {

constructor(navigationService) {
this.availableLinks = navigationService.availableLinks;

LinksController.$inject = ['NavigationService'];


import NavigationService from './navigation-service';
import LinksController from './links-controller';

export default angular.module('app.links', [uirouter])
.service('NavigationService', NavigationService)
.controller('LinksController', LinksController)

Example flowtype output

LinksController.$inject = ['NavigationService'];
^^^^^^^ property `$inject`. Property not found


The reason for this is that by creating a class you are defining its interface in Flow.

When you are assigning $inject to the class you are effectively adding a new property that was not defined in the class interface and that is a type error in Flow.

You have two options for making this type check in Flow:

Adding a static property type definition:

class LinksController {
  static $inject: Array<string>;
  constructor() {...}

LinksController.$inject = ['NavigationService'];

Adding a static property:

class LinksController {
  static $inject = ['NavigationService'];
  constructor() {...}

With the second option you are going to need to enable esproposal.class_static_fields=enable within the [options] section of your .flowconfig

Because this is a proposal not yet added to the JavaScript standard and not available in any browsers, you will also need to compile it with something like Babel (you'll need either the stage-2 preset or the transform-class-properties plugin).