简体   繁体   中英

Import pattern for in Typescript with AngularJS?

This may be Typescript 101 but can't seem to get a clear answer for this.

I am new to Typescript and have come across some existing code (its AngularJS) that follows this format

module App.Login {
    import IStateService = angular.ui.IStateService;

    export class LoginController {

        private _state: IStateService;

        constructor($state: angular.ui.IStateService, ...) {
            this._state = $state;
        }
    }
}

Through reading around and some experimentation I discovered this can be rewritten in a far leaner manner as the following:

module App.Login {  
    export class LoginController {

        constructor(private $state: angular.ui.IStateService, ...) {
        }
    }
}

My questions are:

  • Why was it created the first way originally? Lack of knowledge or for some reason I don't understand
  • Why we need to use import just to alias the interface
  • A question of style, but later in my class to use $state I have to use this.$state . Coming from Angular v1 this feels odd, I presume this is ok though?
  1. Why was it originally this way? If you mean the import, convenience. angular.ui.IStateService is right on the edge of annoyingly long. They author probably just wanted a more convenient version. If you mean the declaration of the private var, some folks (especially coming from a C#/Java background) would prefer to declare class parameters explicitly. The visibility modifier ( public / protected / private ) on constructor parameters syntax is pretty unique to typescript so folks aren't used to it / don't like it.
  2. You don't. You can use the type keyword instead.
  3. Yep, that's totally fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM