From d9f74ddaa65574050f8d7e71503a91cef9f165c2 Mon Sep 17 00:00:00 2001 From: Yaroslav Serhieiev Date: Wed, 25 Jan 2017 11:31:32 +0200 Subject: [PATCH] angular: added tslint validation to the folder; made the code compliant to tslint --- angular-gridster/index.d.ts | 8 +- angular/angular-component-router.d.ts | 4 +- angular/angular-tests.ts | 448 +++++++++++++------------- angular/index.d.ts | 91 +++--- angular/tslint.json | 20 ++ 5 files changed, 294 insertions(+), 277 deletions(-) create mode 100644 angular/tslint.json diff --git a/angular-gridster/index.d.ts b/angular-gridster/index.d.ts index de60d6377b..fc0e990d41 100644 --- a/angular-gridster/index.d.ts +++ b/angular-gridster/index.d.ts @@ -32,7 +32,7 @@ declare module "angular" { // width of grid columns. "auto" will divide the width of the grid evenly among the columns colWidth?: string; - // height of grid rows. 'match' will make it the same as the column width, a numeric value will be interpreted as pixels, + // height of grid rows. 'match' will make it the same as the column width, a numeric value will be interpreted as pixels, // '/2' is half the column width, '*5' is five times the column width, etc. rowHeight?: string; @@ -84,7 +84,7 @@ declare module "angular" { // options to pass to resizable handler resizable?: { - // whether the items are resizable + // whether the items are resizable enabled?: boolean; // location of the resize handles @@ -104,7 +104,7 @@ declare module "angular" { // options to pass to draggable handler draggable?: { - // whether the items are resizable + // whether the items are resizable enabled?: boolean; // Distance in pixels from the edge of the viewport after which the viewport should scroll, relative to pointer @@ -142,4 +142,4 @@ declare module "angular" { col: number; } } -} \ No newline at end of file +} diff --git a/angular/angular-component-router.d.ts b/angular/angular-component-router.d.ts index 99ae821c72..92458331d6 100644 --- a/angular/angular-component-router.d.ts +++ b/angular/angular-component-router.d.ts @@ -1,9 +1,9 @@ +/* tslint:disable:dt-header variable-name */ // Type definitions for Angular JS 1.5 component router // Project: http://angularjs.org // Definitions by: David Reher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - declare namespace angular { /** * `Instruction` is a tree of {@link ComponentInstruction}s with all the information needed @@ -263,7 +263,7 @@ declare namespace angular { /** * Subscribe to URL updates from the router */ - subscribe(onNext: (value: any) => void): Object; + subscribe(onNext: (value: any) => void): {}; /** * Removes the contents of this router's outlet and all descendant outlets diff --git a/angular/angular-tests.ts b/angular/angular-tests.ts index c6ee7c7a00..1a4841ab8c 100644 --- a/angular/angular-tests.ts +++ b/angular/angular-tests.ts @@ -1,4 +1,3 @@ - // issue: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/369 // https://github.com/witoldsz/angular-http-auth/blob/master/src/angular-http-auth.js /** @@ -7,12 +6,14 @@ * License: MIT */ +/* tslint:disable:no-empty no-shadowed-variable */ + class AuthService { /** * Holds all the requests which failed due to 401 response, * so they can be re-requested in future, once login is completed. */ - buffer: { config: ng.IRequestConfig; deferred: ng.IDeferred; }[] = []; + buffer: Array<{ config: ng.IRequestConfig; deferred: ng.IDeferred; }> = []; /** * Required by HTTP interceptor. @@ -20,34 +21,35 @@ class AuthService { */ pushToBuffer = function(config: ng.IRequestConfig, deferred: ng.IDeferred) { this.buffer.push({ - config: config, - deferred: deferred + config, + deferred }); - } + }; $get = [ - '$rootScope', '$injector', function($rootScope: ng.IScope, $injector: ng.auto.IInjectorService) { - var $http: ng.IHttpService; //initialized later because of circular dependency problem + '$rootScope', '$injector', function($rootScope: ng.IScope, $injector: ng.auto.IInjectorService) { + let $http: ng.IHttpService; //initialized later because of circular dependency problem function retry(config: ng.IRequestConfig, deferred: ng.IDeferred) { $http = $http || $injector.get('$http'); - $http(config).then(function (response) { + $http(config).then(function(response) { deferred.resolve(response); }); } function retryAll() { - for (var i = 0; i < this.buffer.length; ++i) { - retry(this.buffer[i].config, this.buffer[i].deferred); + for (const request of this.buffer) { + retry(request.config, request.deferred); } + this.buffer = []; } return { - loginConfirmed: function () { + loginConfirmed() { $rootScope.$broadcast('event:auth-loginConfirmed'); retryAll(); } - } - } + }; + } as any ]; } @@ -59,20 +61,20 @@ angular.module('http-auth-interceptor', []) * $http interceptor. * On 401 response - it stores the request and broadcasts 'event:angular-auth-loginRequired'. */ - .config(['$httpProvider', 'authServiceProvider', function ($httpProvider: ng.IHttpProvider, authServiceProvider: any) { + .config(['$httpProvider', 'authServiceProvider', function($httpProvider: ng.IHttpProvider, authServiceProvider: any) { - $httpProvider.defaults.headers.common = {'Authorization': 'Bearer token'}; + $httpProvider.defaults.headers.common = {Authorization: 'Bearer token'}; $httpProvider.defaults.headers.get['Authorization'] = 'Bearer token'; - $httpProvider.defaults.headers.post['Authorization'] = function (config:ng.IRequestConfig):string { return 'Bearer token'; } + $httpProvider.defaults.headers.post['Authorization'] = function(config: ng.IRequestConfig): string { return 'Bearer token'; }; - var interceptor = ['$rootScope', '$q', function ($rootScope: ng.IScope, $q: ng.IQService) { + const interceptor = ['$rootScope', '$q', function($rootScope: ng.IScope, $q: ng.IQService) { function success(response: ng.IHttpPromiseCallbackArg) { return response; } function error(response: ng.IHttpPromiseCallbackArg) { if (response.status === 401) { - var deferred = $q.defer(); + const deferred = $q.defer(); authServiceProvider.pushToBuffer(response.config, deferred); $rootScope.$broadcast('event:auth-loginRequired'); return deferred.promise; @@ -81,14 +83,13 @@ angular.module('http-auth-interceptor', []) return $q.reject(response); } - return function (promise: ng.IHttpPromise) { + return function(promise: ng.IHttpPromise) { return promise.then(success, error); - } + }; - }]; + } as any]; $httpProvider.interceptors.push(interceptor); - }]); - + } as any]); namespace HttpAndRegularPromiseTests { interface Person { @@ -96,7 +97,7 @@ namespace HttpAndRegularPromiseTests { lastName: string; } - interface ExpectedResponse extends Person { } + type ExpectedResponse = Person; interface SomeControllerScope extends ng.IScope { person: Person; @@ -106,13 +107,13 @@ namespace HttpAndRegularPromiseTests { nothing?: string; } - var someController: Function = ($scope: SomeControllerScope, $http: ng.IHttpService, $q: ng.IQService) => { - $http.get("http://somewhere/some/resource") + function someController($scope: SomeControllerScope, $http: ng.IHttpService, $q: ng.IQService) { + $http.get('http://somewhere/some/resource') .success((data: ExpectedResponse) => { $scope.person = data; }); - $http.get("http://somewhere/some/resource") + $http.get('http://somewhere/some/resource') .then((response: ng.IHttpPromiseCallbackArg) => { // typing lost, so something like // var i: number = response.data @@ -120,7 +121,7 @@ namespace HttpAndRegularPromiseTests { $scope.person = response.data; }); - $http.get("http://somewhere/some/resource") + $http.get('http://somewhere/some/resource') .then((response: ng.IHttpPromiseCallbackArg) => { // typing lost, so something like // var i: number = response.data @@ -128,47 +129,48 @@ namespace HttpAndRegularPromiseTests { $scope.person = response.data; }); - var aPromise: ng.IPromise = $q.when({ firstName: "Jack", lastName: "Sparrow" }); + const aPromise: ng.IPromise = $q.when({ firstName: 'Jack', lastName: 'Sparrow' }); aPromise.then((person: Person) => { $scope.person = person; }); - var bPromise: ng.IPromise = $q.when(42); + const bPromise: ng.IPromise = $q.when(42); bPromise.then((answer: number) => { $scope.theAnswer = answer; }); - var cPromise: ng.IPromise = $q.when(["a", "b", "c"]); + const cPromise: ng.IPromise = $q.when(['a', 'b', 'c']); cPromise.then((letters: string[]) => { $scope.letters = letters; }); // When $q.when is passed an IPromise, it returns an IPromise - var dPromise: ng.IPromise = $q.when($q.when("ALBATROSS!")); + const dPromise: ng.IPromise = $q.when($q.when('ALBATROSS!')); dPromise.then((snack: string) => { $scope.snack = snack; }); // $q.when may be called without arguments - var ePromise: ng.IPromise = $q.when(); + const ePromise: ng.IPromise = $q.when(); ePromise.then(() => { - $scope.nothing = "really nothing"; + $scope.nothing = 'really nothing'; }); } - // Test that we can pass around a type-checked success/error Promise Callback - var anotherController: Function = ($scope: SomeControllerScope, $http: - ng.IHttpService, $q: ng.IQService) => { - - var buildFooData: Function = () => 42; - - var doFoo: Function = (callback: ng.IHttpPromiseCallback) => { - $http.get('/foo', buildFooData()) - .success(callback); + // Test that we can pass around a type-checked success/error Promise Callback + function anotherController($scope: SomeControllerScope, $http: ng.IHttpService, $q: ng.IQService) { + function buildFooData(): ng.IRequestShortcutConfig { + return {}; } - doFoo((data: any) => console.log(data)); - } + function doFoo(callback: ng.IHttpPromiseCallback) { + $http + .get('/foo', buildFooData()) + .success(callback); + }; + + doFoo((data: any) => console.log(data)); + }; } // Test for AngularJS Syntax @@ -178,9 +180,9 @@ namespace My.Namespace { } // IModule Registering Test -var mod = angular.module('tests', []); -mod.controller('name', function ($scope: ng.IScope) { }); -mod.controller('name', ['$scope', function ($scope: ng.IScope) { }]); +let mod = angular.module('tests', []); +mod.controller('name', function($scope: ng.IScope) { }); +mod.controller('name', ['$scope', function($scope: ng.IScope) { }]); mod.controller('name', class { // Uncommenting the next line should lead to a type error because this signature isn't compatible // with the signature of the `$onChanges` hook: @@ -188,7 +190,7 @@ mod.controller('name', class { }); mod.controller({ MyCtrl: class{}, - MyCtrl2: function() {}, + MyCtrl2: function() {}, // tslint:disable-line:object-literal-shorthand MyCtrl3: ['$fooService', function($fooService: any) { }] }); mod.directive('myDirectiveA', ($rootScope: ng.IRootScopeService) => { @@ -201,7 +203,7 @@ mod.directive('myDirectiveA', ($rootScope: ng.IRootScopeService) => { scope.$watch(() => foo, () => el.text(foo)); }; }); -mod.directive('myDirectiveB', ['$rootScope', function ($rootScope: ng.IRootScopeService) { +mod.directive('myDirectiveB', ['$rootScope', function($rootScope: ng.IRootScopeService) { return { link(scope, el, attrs) { el.click(e => { @@ -218,38 +220,37 @@ mod.directive({ template: 'my-bar-dir.tpl.html' })] }); -mod.factory('name', function ($scope: ng.IScope) { }) -mod.factory('name', ['$scope', function ($scope: ng.IScope) { }]) +mod.factory('name', function($scope: ng.IScope) { }); +mod.factory('name', ['$scope', function($scope: ng.IScope) { }]); mod.factory({ - name1: function (foo: any) { }, - name2: ['foo', function (foo: any) { }] + name1: function(foo: any) { }, // tslint:disable-line:object-literal-shorthand + name2: ['foo', function(foo: any) { }] }); -mod.filter('name', function ($scope: ng.IScope) { }) -mod.filter('name', ['$scope', function ($scope: ng.IScope) { }]) +mod.filter('name', function($scope: ng.IScope) { }); +mod.filter('name', ['$scope', function($scope: ng.IScope) { }]); mod.filter({ - name1: function (foo: any) { }, - name2: ['foo', function (foo: any) { }] + name1: function(foo: any) { }, // tslint:disable-line:object-literal-shorthand + name2: ['foo', function(foo: any) { }] }); -mod.provider('name', function ($scope: ng.IScope) { return { $get: () => { } } }) +mod.provider('name', function($scope: ng.IScope) { return { $get: () => { } }; }); mod.provider('name', TestProvider); -mod.provider('name', ['$scope', function ($scope: ng.IScope) { }]) +mod.provider('name', ['$scope', function($scope: ng.IScope) { } as any]); mod.provider(My.Namespace); -mod.service('name', function ($scope: ng.IScope) { }) -mod.service('name', ['$scope', function ($scope: ng.IScope) { }]) +mod.service('name', function($scope: ng.IScope) { }); +mod.service('name', ['$scope', function($scope: ng.IScope) { } as any]); mod.service({ MyCtrl: class{}, - MyCtrl2: function() {}, + MyCtrl2: function() {}, // tslint:disable-line:object-literal-shorthand MyCtrl3: ['$fooService', function($fooService: any) { }] }); mod.constant('name', 23); -mod.constant('name', "23"); +mod.constant('name', '23'); mod.constant(My.Namespace); mod.value('name', 23); -mod.value('name', "23"); +mod.value('name', '23'); mod.value(My.Namespace); -mod.decorator('name', function($scope:ng.IScope){ }); -mod.decorator('name', ['$scope', function($scope: ng.IScope){ }]); - +mod.decorator('name', function($scope: ng.IScope) {}); +mod.decorator('name', ['$scope', function($scope: ng.IScope) {} as any]); class TestProvider implements ng.IServiceProvider { constructor(private $scope: ng.IScope) { @@ -261,23 +262,23 @@ class TestProvider implements ng.IServiceProvider { // QProvider tests angular.module('qprovider-test', []) - .config(['$qProvider', function ($qProvider: ng.IQProvider) { + .config(['$qProvider', function($qProvider: ng.IQProvider) { const provider: ng.IQProvider = $qProvider.errorOnUnhandledRejections(false); const currentValue: boolean = $qProvider.errorOnUnhandledRejections(); }]); // Promise signature tests -var foo: ng.IPromise; +let foo: ng.IPromise; foo.then((x) => { // x is inferred to be a number - return "asdf"; + return 'asdf'; }).then((x) => { // x is inferred to be string - x.length; + const len = x.length; return 123; }).then((x) => { // x is infered to be a number - x.toFixed(); + const fixed = x.toFixed(); return; }).then((x) => { // x is infered to be void @@ -336,15 +337,14 @@ namespace TestQ { result = $q.all([promiseAny, promiseAny]); } { - let result: angular.IPromise<{[id: string]: any;}>; + let result: angular.IPromise<{[id: string]: any; }>; result = $q.all({a: promiseAny, b: promiseAny}); } { - let result: angular.IPromise<{a: number; b: string;}>; - result = $q.all<{a: number; b: string;}>({a: promiseAny, b: promiseAny}); + let result: angular.IPromise<{a: number; b: string; }>; + result = $q.all<{a: number; b: string; }>({a: promiseAny, b: promiseAny}); } - // $q.defer { let result: angular.IDeferred; @@ -397,11 +397,10 @@ namespace TestQ { } } - -var httpFoo: ng.IHttpPromise; +let httpFoo: ng.IHttpPromise; httpFoo.then((x) => { // When returning a promise the generic type must be inferred. - var innerPromise : ng.IPromise; + var innerPromise: ng.IPromise; return innerPromise; }).then((x) => { // must still be number. @@ -409,13 +408,12 @@ httpFoo.then((x) => { }); httpFoo.success((data, status, headers, config) => { - var h = headers("test"); + const h = headers('test'); h.charAt(0); - var hs = headers(); - hs["content-type"].charAt(1); + const hs = headers(); + hs['content-type'].charAt(1); }); - // Deferred signature tests namespace TestDeferred { var any: any; @@ -432,8 +430,8 @@ namespace TestDeferred { // deferred.resolve { let result: void; - result = deferred.resolve(); - result = deferred.resolve(tResult); + result = deferred.resolve() as void; + result = deferred.resolve(tResult) as void; } // deferred.reject @@ -458,7 +456,7 @@ namespace TestDeferred { } namespace TestInjector { - let $injector: angular.auto.IInjectorService; + var $injector: angular.auto.IInjectorService; $injector.strictDi = true; @@ -466,10 +464,9 @@ namespace TestInjector { $injector.annotate(() => {}, true); } - // Promise signature tests namespace TestPromise { - var result: any; + let result: any; var any: any; interface TResult { @@ -494,63 +491,61 @@ namespace TestPromise { var promise: angular.IPromise; // promise.then - result = >promise.then((result) => any); - result = >promise.then((result) => any, (any) => any); - result = >promise.then((result) => any, (any) => any, (any) => any); + result = promise.then((result) => any) as angular.IPromise; + result = promise.then((result) => any, (any) => any) as angular.IPromise; + result = promise.then((result) => any, (any) => any, (any) => any) as angular.IPromise; - result = >promise.then((result) => result); - result = >promise.then((result) => result, (any) => any); - result = >promise.then((result) => result, (any) => any, (any) => any); - result = >promise.then((result) => tresultPromise); - result = >promise.then((result) => tresultPromise, (any) => any); - result = >promise.then((result) => tresultPromise, (any) => any, (any) => any); - result = >>promise.then((result) => tresultHttpPromise); - result = >>promise.then((result) => tresultHttpPromise, (any) => any); - result = >>promise.then((result) => tresultHttpPromise, (any) => any, (any) => any); + result = promise.then((result) => result) as angular.IPromise; + result = promise.then((result) => result, (any) => any) as angular.IPromise; + result = promise.then((result) => result, (any) => any, (any) => any) as angular.IPromise; + result = promise.then((result) => tresultPromise) as angular.IPromise; + result = promise.then((result) => tresultPromise, (any) => any) as angular.IPromise; + result = promise.then((result) => tresultPromise, (any) => any, (any) => any) as angular.IPromise; + result = promise.then((result) => tresultHttpPromise) as angular.IPromise>; + result = promise.then((result) => tresultHttpPromise, (any) => any) as angular.IPromise>; + result = promise.then((result) => tresultHttpPromise, (any) => any, (any) => any) as angular.IPromise>; - result = >promise.then((result) => tother); - result = >promise.then((result) => tother, (any) => any); - result = >promise.then((result) => tother, (any) => any, (any) => any); - result = >promise.then((result) => totherPromise); - result = >promise.then((result) => totherPromise, (any) => any); - result = >promise.then((result) => totherPromise, (any) => any, (any) => any); - result = >>promise.then((result) => totherHttpPromise); - result = >>promise.then((result) => totherHttpPromise, (any) => any); - result = >>promise.then((result) => totherHttpPromise, (any) => any, (any) => any); + result = promise.then((result) => tother) as angular.IPromise; + result = promise.then((result) => tother, (any) => any) as angular.IPromise; + result = promise.then((result) => tother, (any) => any, (any) => any) as angular.IPromise; + result = promise.then((result) => totherPromise) as angular.IPromise; + result = promise.then((result) => totherPromise, (any) => any) as angular.IPromise; + result = promise.then((result) => totherPromise, (any) => any, (any) => any) as angular.IPromise; + result = promise.then((result) => totherHttpPromise) as angular.IPromise>; + result = promise.then((result) => totherHttpPromise, (any) => any) as angular.IPromise>; + result = promise.then((result) => totherHttpPromise, (any) => any, (any) => any) as angular.IPromise>; // promise.catch - result = >promise.catch((err) => any); - result = >promise.catch((err) => tresult); - result = >promise.catch((err) => tresultPromise); - result = >>promise.catch((err) => tresultHttpPromise); - result = >promise.catch((err) => tother); - result = >promise.catch((err) => totherPromise); - result = >>promise.catch((err) => totherHttpPromise); + result = promise.catch((err) => any) as angular.IPromise; + result = promise.catch((err) => tresult) as angular.IPromise; + result = promise.catch((err) => tresultPromise) as angular.IPromise; + result = promise.catch((err) => tresultHttpPromise) as angular.IPromise>; + result = promise.catch((err) => tother) as angular.IPromise; + result = promise.catch((err) => totherPromise) as angular.IPromise; + result = promise.catch((err) => totherHttpPromise) as angular.IPromise>; // promise.finally - result = >promise.finally(() => any); - result = >promise.finally(() => tresult); - result = >promise.finally(() => tother); + result = promise.finally(() => any) as angular.IPromise; + result = promise.finally(() => tresult) as angular.IPromise; + result = promise.finally(() => tother) as angular.IPromise; } - function test_angular_forEach() { - var values: { [key: string]: string } = { name: 'misko', gender: 'male' }; - var log: string[] = []; - angular.forEach(values, function (value, key) { + const values: { [key: string]: string } = { name: 'misko', gender: 'male' }; + const log: string[] = []; + angular.forEach(values, function(value, key) { this.push(key + ': ' + value); }, log); //expect(log).toEqual(['name: misko', 'gender: male']); } // angular.element() tests -var element = angular.element("div.myApp"); -var scope: ng.IScope = element.scope(); -var isolateScope: ng.IScope = element.isolateScope(); +let element = angular.element('div.myApp'); +let scope: ng.IScope = element.scope(); +let isolateScope: ng.IScope = element.isolateScope(); isolateScope = element.find('div.foo').isolateScope(); isolateScope = element.children().isolateScope(); - // $timeout signature tests namespace TestTimeout { interface TResult { @@ -590,25 +585,24 @@ namespace TestTimeout { } } - -function test_IAttributes(attributes: ng.IAttributes){ +function test_IAttributes(attributes: ng.IAttributes) { return attributes; } test_IAttributes({ - $normalize: function (classVal){ return "foo" }, - $addClass: function (classVal){}, - $removeClass: function(classVal){}, - $updateClass: function(newClass, oldClass){}, - $set: function(key, value){}, - $observe: function(name: any, fn: any){ + $normalize(classVal) { return 'foo'; }, + $addClass(classVal) {}, + $removeClass(classVal) {}, + $updateClass(newClass, oldClass) {}, + $set(key, value) {}, + $observe(name: any, fn: any) { return fn; }, $attr: {} }); class SampleDirective implements ng.IDirective { - public restrict = 'A'; + restrict = 'A'; name = 'doh'; compile(templateElement: ng.IAugmentedJQuery) { @@ -617,7 +611,7 @@ class SampleDirective implements ng.IDirective { }; } - static instance():ng.IDirective { + static instance(): ng.IDirective { return new SampleDirective(); } @@ -627,7 +621,7 @@ class SampleDirective implements ng.IDirective { } class SampleDirective2 implements ng.IDirective { - public restrict = 'EAC'; + restrict = 'EAC'; compile(templateElement: ng.IAugmentedJQuery) { return { @@ -635,7 +629,7 @@ class SampleDirective2 implements ng.IDirective { }; } - static instance():ng.IDirective { + static instance(): ng.IDirective { return new SampleDirective2(); } @@ -654,7 +648,7 @@ angular.module('AnotherSampleDirective', []).directive('myDirective', ['$interpo $interpolate('', true)(scope); $interpolate('', true, 'html')(scope); $interpolate('', true, 'html', true)(scope); - var defer = $q.defer(); + const defer = $q.defer(); defer.reject(); defer.resolve(); defer.promise.then(function(d) { @@ -670,7 +664,7 @@ angular.module('AnotherSampleDirective', []).directive('myDirective', ['$interpo .finally((): any => { return null; }); - var promise = new $q((resolve) => { + let promise = new $q((resolve) => { resolve(); }); @@ -785,25 +779,25 @@ angular.module('docsTimeDirective', []) .directive('myCurrentTime', ['$interval', 'dateFilter', function($interval: any, dateFilter: any) { return { - link: function(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs:ng.IAttributes) { - var format: any, + link(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) { + let format: any, timeoutId: any; function updateTime() { element.text(dateFilter(new Date(), format)); } - scope.$watch(attrs['myCurrentTime'], function (value: any) { + scope.$watch(attrs['myCurrentTime'], function(value: any) { format = value; updateTime(); }); - element.on('$destroy', function () { + element.on('$destroy', function() { $interval.cancel(timeoutId); }); // start the UI update process; save the timeoutId for canceling - timeoutId = $interval(function () { + timeoutId = $interval(function() { updateTime(); // update DOM }, 1000); } @@ -832,19 +826,18 @@ angular.module('docsTransclusionExample', []) transclude: true, scope: {}, templateUrl: 'my-dialog.html', - link: function (scope: ng.IScope, element: ng.IAugmentedJQuery) { + link(scope: ng.IScope, element: ng.IAugmentedJQuery) { scope['name'] = 'Jeff'; } }; }); - angular.module('docsIsoFnBindExample', []) .controller('Controller', ['$scope', '$timeout', function($scope: any, $timeout: any) { $scope.name = 'Tobias'; - $scope.hideDialog = function () { + $scope.hideDialog = function() { $scope.dialogIsHidden = true; - $timeout(function () { + $timeout(function() { $scope.dialogIsHidden = false; }, 2000); }; @@ -854,7 +847,7 @@ angular.module('docsIsoFnBindExample', []) restrict: 'E', transclude: true, scope: { - 'close': '&onClose' + close: '&onClose' }, templateUrl: 'my-dialog-close.html' }; @@ -863,7 +856,7 @@ angular.module('docsIsoFnBindExample', []) angular.module('dragModule', []) .directive('myDraggable', ['$document', function($document: any) { return function(scope: any, element: any, attr: any) { - var startX = 0, startY = 0, x = 0, y = 0; + let startX = 0, startY = 0, x = 0, y = 0; element.css({ position: 'relative', @@ -903,8 +896,8 @@ angular.module('docsTabsExample', []) restrict: 'E', transclude: true, scope: {}, - controller: function($scope: ng.IScope) { - var panes: any = $scope['panes'] = []; + controller($scope: ng.IScope) { + const panes: any = $scope['panes'] = []; $scope['select'] = function(pane: any) { angular.forEach(panes, function(pane: any) { @@ -931,7 +924,7 @@ angular.module('docsTabsExample', []) scope: { title: '@' }, - link: function(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, tabsCtrl: any) { + link(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, tabsCtrl: any) { tabsCtrl.addPane(scope); }, templateUrl: 'my-pane.html' @@ -945,7 +938,7 @@ angular.module('multiSlotTranscludeExample', []) button: 'button', list: 'ul', }, - link: function(scope, element, attrs, ctrl, transclude) { + link(scope, element, attrs, ctrl, transclude) { // without scope transclude().appendTo(element); transclude(clone => clone.appendTo(element)); @@ -960,52 +953,52 @@ angular.module('multiSlotTranscludeExample', []) angular.module('componentExample', []) .component('counter', { - require: {'ctrl': '^ctrl'}, + require: {ctrl: '^ctrl'}, bindings: { count: '=' }, controller: 'CounterCtrl', controllerAs: 'counterCtrl', - template: function () { + template() { return ''; }, transclude: { - 'el': 'target' + el: 'target' } }) .component('anotherCounter', { - controller: function(){}, + controller() {}, require: { - 'parent': '^parentCtrl' + parent: '^parentCtrl' }, template: '', transclude: true }); -interface copyExampleUser { +interface ICopyExampleUser { name?: string; email?: string; gender?: string; } -interface copyExampleScope { +interface ICopyExampleScope { - user: copyExampleUser; - master: copyExampleUser; - update: (copyExampleUser: copyExampleUser) => any; + user: ICopyExampleUser; + master: ICopyExampleUser; + update: (copyExampleUser: ICopyExampleUser) => any; reset: () => any; } angular.module('copyExample', []) - .controller('ExampleController', ['$scope', function ($scope: copyExampleScope) { + .controller('ExampleController', ['$scope', function($scope: ICopyExampleScope) { $scope.master = { }; - $scope.update = function (user) { + $scope.update = function(user) { // Example with 1 argument $scope.master = angular.copy(user); }; - $scope.reset = function () { + $scope.reset = function() { // Example with 2 arguments angular.copy($scope.master, $scope.user); }; @@ -1022,9 +1015,14 @@ namespace locationTests { */ // given url http://example.com/#/some/path?foo=bar&baz=xoxo - var searchObject = $location.search(); + const searchObject = $location.search(); // => {foo: 'bar', baz: 'xoxo'} + function assert(condition: boolean) { + if (!condition) { + throw new Error(); + } + } // set foo to 'yipee' $location.search('foo', 'yipee'); @@ -1041,29 +1039,29 @@ namespace locationTests { // in browser with HTML5 history support: // open http://example.com/#!/a -> rewrite to http://example.com/a // (replacing the http://example.com/#!/a history record) - $location.path() == '/a' + assert($location.path() === '/a'); $location.path('/foo'); - $location.absUrl() == 'http://example.com/foo' + assert($location.absUrl() === 'http://example.com/foo'); - $location.search() == {} + assert($location.search() === {}); $location.search({ a: 'b', c: true }); - $location.absUrl() == 'http://example.com/foo?a=b&c' + assert($location.absUrl() === 'http://example.com/foo?a=b&c'); $location.path('/new').search('x=y'); - $location.url() == 'new?x=y' - $location.absUrl() == 'http://example.com/new?x=y' + assert($location.url() === 'new?x=y'); + assert($location.absUrl() === 'http://example.com/new?x=y'); // in browser without html5 history support: // open http://example.com/new?x=y -> redirect to http://example.com/#!/new?x=y // (again replacing the http://example.com/new?x=y history item) - $location.path() == '/new' - $location.search() == { x: 'y' } + assert($location.path() === '/new'); + assert($location.search() === { x: 'y' }); $location.path('/foo/bar'); - $location.path() == '/foo/bar' - $location.url() == '/foo/bar?x=y' - $location.absUrl() == 'http://example.com/#!/foo/bar?x=y' + assert($location.path() === '/foo/bar'); + assert($location.url() === '/foo/bar?x=y'); + assert($location.absUrl() === 'http://example.com/#!/foo/bar?x=y'); } // NgModelController @@ -1074,7 +1072,7 @@ function NgModelControllerTyping() { // See https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#$validators ngModel.$validators['validCharacters'] = function(modelValue, viewValue) { - var value = modelValue || viewValue; + const value = modelValue || viewValue; return /[0-9]+/.test(value) && /[a-z]+/.test(value) && /[A-Z]+/.test(value) && @@ -1082,7 +1080,7 @@ function NgModelControllerTyping() { }; ngModel.$asyncValidators['uniqueUsername'] = function(modelValue, viewValue) { - var value = modelValue || viewValue; + const value = modelValue || viewValue; return $http.get('/api/users/' + value). then(function resolved() { return $q.reject('exists'); @@ -1092,67 +1090,67 @@ function NgModelControllerTyping() { }; } -var $filter: angular.IFilterService; +let $filter: angular.IFilterService; function testFilter() { var items: string[]; - $filter("filter")(items, "test"); - $filter("filter")(items, {name: "test"}); - $filter("filter")(items, (val, index, array) => { + $filter('filter')(items, 'test'); + $filter('filter')(items, {name: 'test'}); + $filter('filter')(items, (val, index, array) => { return true; }); - $filter("filter")(items, (val, index, array) => { + $filter('filter')(items, (val, index, array) => { return true; }, (actual, expected) => { - return actual == expected; + return actual === expected; }); } function testCurrency() { - $filter("currency")(126); - $filter("currency")(126, "$", 2); + $filter('currency')(126); + $filter('currency')(126, '$', 2); } function testNumber() { - $filter("number")(167); - $filter("number")(167, 2); + $filter('number')(167); + $filter('number')(167, 2); } function testDate() { - $filter("date")(new Date()); - $filter("date")(new Date(), 'yyyyMMdd'); - $filter("date")(new Date(), 'yyyyMMdd', '+0430'); + $filter('date')(new Date()); + $filter('date')(new Date(), 'yyyyMMdd'); + $filter('date')(new Date(), 'yyyyMMdd', '+0430'); } function testJson() { - var json: string = $filter("json")({test:true}, 2); + const json: string = $filter('json')({test: true}, 2); } function testLowercase() { - var lower: string = $filter("lowercase")('test'); + const lower: string = $filter('lowercase')('test'); } function testUppercase() { - var lower: string = $filter("uppercase")('test'); + const lower: string = $filter('uppercase')('test'); } function testLimitTo() { - var limitTo = $filter("limitTo"); - var filtered: number[] = $filter("limitTo")([1,2,3], 5); - filtered = $filter("limitTo")([1,2,3], 5, 2); + const limitTo = $filter('limitTo'); + let filtered: number[] = $filter('limitTo')([1, 2, 3], 5); + filtered = $filter('limitTo')([1, 2, 3], 5, 2); - var filteredString: string = $filter("limitTo")("124", 4); - filteredString = $filter("limitTo")(124, 4); + let filteredString: string = $filter('limitTo')('124', 4); + filteredString = $filter('limitTo')(124, 4); } function testOrderBy() { - var filtered: number[] = $filter("orderBy")([1,2,3], "test"); - filtered = $filter("orderBy")([1,2,3], "test", true); - filtered = $filter("orderBy")([1,2,3], ['prop1', 'prop2']); - filtered = $filter("orderBy")([1,2,3], (val: number) => 1); - var filtered2: string[] = $filter("orderBy")(["1","2","3"], (val: string) => 1); - filtered2 = $filter("orderBy")(["1","2","3"], [ + let filtered: number[] = $filter('orderBy')([1, 2, 3], 'test'); + filtered = $filter('orderBy')([1, 2, 3], 'test', true); + filtered = $filter('orderBy')([1, 2, 3], ['prop1', 'prop2']); + filtered = $filter('orderBy')([1, 2, 3], (val: number) => 1); + let filtered2: string[] = $filter('orderBy')(['1', '2', '3'], (val: string) => 1); + filtered2 = $filter('orderBy')(['1', '2', '3'], [ (val: string) => 1, (val: string) => 2 ]); @@ -1160,28 +1158,26 @@ function testOrderBy() { function testDynamicFilter() { // Test with separate variables - var dateFilter = $filter("date"); - var myDate = new Date(); - dateFilter(myDate , "EEE, MMM d"); + const dateFilter = $filter('date'); + const myDate = new Date(); + dateFilter(myDate , 'EEE, MMM d'); // Test with dynamic name - var filterName = 'date'; - var dynDateFilter = $filter(filterName); + const filterName = 'date'; + const dynDateFilter = $filter(filterName); dynDateFilter(new Date()); } -interface MyCustomFilter { - (value: string): string; -} +type MyCustomFilter = (value: string) => string; function testCustomFilter() { - var filterCustom = $filter('custom'); - var filtered: string = filterCustom("test"); + const filterCustom = $filter('custom'); + const filtered: string = filterCustom('test'); } function parseTyping() { var $parse: angular.IParseService; - var compiledExp = $parse('a.b.c'); + const compiledExp = $parse('a.b.c'); if (compiledExp.constant) { return compiledExp({}); } else if (compiledExp.literal) { @@ -1191,8 +1187,8 @@ function parseTyping() { function parseWithParams() { var $parse: angular.IParseService; - var compiledExp = $parse('a.b.c', () => null); - var compiledExp = $parse('a.b.c', null, false); + const compiledExp1 = $parse('a.b.c', () => null); + const compiledExp2 = $parse('a.b.c', null, false); } function doBootstrap(element: Element | JQuery, mode: string): ng.auto.IInjectorService { @@ -1211,8 +1207,8 @@ function doBootstrap(element: Element | JQuery, mode: string): ng.auto.IInjector } function testIHttpParamSerializerJQLikeProvider() { - let serializer: angular.IHttpParamSerializer; + var serializer: angular.IHttpParamSerializer; serializer({ - a: "b" + a: 'b' }); } diff --git a/angular/index.d.ts b/angular/index.d.ts index f3f9fc87a6..3f094f3185 100644 --- a/angular/index.d.ts +++ b/angular/index.d.ts @@ -27,7 +27,7 @@ import ng = angular; /////////////////////////////////////////////////////////////////////////////// declare namespace angular { - type Injectable = T | (string | T)[]; + type Injectable = T | Array; // not directly implemented, but ensures that constructed class implements $get interface IServiceProviderClass { @@ -64,7 +64,7 @@ declare namespace angular { * @param config an object for defining configuration options for the application. The following keys are supported: * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. */ - bootstrap(element: string|Element|JQuery|Document, modules?: (string|Function|any[])[], config?: IAngularBootstrapConfig): auto.IInjectorService; + bootstrap(element: string|Element|JQuery|Document, modules?: Array, config?: IAngularBootstrapConfig): auto.IInjectorService; /** * Creates a deep copy of source, which should be an object or an array. @@ -122,7 +122,7 @@ declare namespace angular { fromJson(json: string): any; identity(arg?: T): T; injector(modules?: any[], strictDi?: boolean): auto.IInjectorService; - isArray(value: any): value is Array; + isArray(value: any): value is any[]; isDate(value: any): value is Date; isDefined(value: any): boolean; isElement(value: any): boolean; @@ -514,7 +514,7 @@ declare namespace angular { $watchCollection(watchExpression: (scope: IScope) => T, listener: (newValue: T, oldValue: T, scope: IScope) => any): () => void; $watchGroup(watchExpressions: any[], listener: (newValue: any, oldValue: any, scope: IScope) => any): () => void; - $watchGroup(watchExpressions: { (scope: IScope): any }[], listener: (newValue: any, oldValue: any, scope: IScope) => any): () => void; + $watchGroup(watchExpressions: Array<{ (scope: IScope): any }>, listener: (newValue: any, oldValue: any, scope: IScope) => any): () => void; $parent: IScope; $root: IRootScopeService; @@ -662,9 +662,9 @@ declare namespace angular { } interface IFilterOrderByItem { - value: any, - type: string, - index: any + value: any; + type: string; + index: any; } interface IFilterOrderByComparatorFunc { @@ -756,7 +756,7 @@ declare namespace angular { * @param comparator Function used to determine the relative order of value pairs. * @return An array containing the items from the specified collection, ordered by a comparator function based on the values computed using the expression predicate. */ - (array: T[], expression: string|((value: T) => any)|(((value: T) => any)|string)[], reverse?: boolean, comparator?: IFilterOrderByComparatorFunc): T[]; + (array: T[], expression: string|((value: T) => any)|Array<((value: T) => any)|string>, reverse?: boolean, comparator?: IFilterOrderByComparatorFunc): T[]; } /** @@ -1023,7 +1023,7 @@ declare namespace angular { all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise, T4 | IPromise ]): IPromise<[T1, T2, T3, T4]>; all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise]): IPromise<[T1, T2, T3]>; all(values: [T1 | IPromise, T2 | IPromise]): IPromise<[T1, T2]>; - all(promises: IPromise[]): IPromise; + all(promises: Array>): IPromise; /** * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. * @@ -1284,11 +1284,11 @@ declare namespace angular { } interface ITemplateLinkingFunctionOptions { - parentBoundTranscludeFn?: ITranscludeFunction, + parentBoundTranscludeFn?: ITranscludeFunction; transcludeControllers?: { [controller: string]: { instance: IController } - }, - futureParentElement?: JQuery + }; + futureParentElement?: JQuery; } /** @@ -1510,7 +1510,9 @@ declare namespace angular { (data: any, headersGetter: IHttpHeadersGetter, status: number): any; } - type HttpHeaderType = {[requestType: string]:string|((config:IRequestConfig) => string)}; + interface HttpHeaderType { + [requestType: string]: string|((config: IRequestConfig) => string); + } interface IHttpRequestConfigHeaders { [requestType: string]: any; @@ -1593,7 +1595,7 @@ declare namespace angular { * Register service factories (names or implementations) for interceptors which are called before and after * each request. */ - interceptors: (string | Injectable)[]; + interceptors: Array>; useApplyAsync(): boolean; useApplyAsync(value: boolean): IHttpProvider; @@ -1603,7 +1605,7 @@ declare namespace angular { * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining. * otherwise, returns the current configured value. */ - useLegacyPromiseExtensions(value:boolean) : boolean | IHttpProvider; + useLegacyPromiseExtensions(value: boolean): boolean | IHttpProvider; } /////////////////////////////////////////////////////////////////////////// @@ -1687,16 +1689,15 @@ declare namespace angular { valueOf(value: any): any; } - /////////////////////////////////////////////////////////////////////////// // SCEDelegateProvider // see http://docs.angularjs.org/api/ng.$sceDelegateProvider /////////////////////////////////////////////////////////////////////////// interface ISCEDelegateProvider extends IServiceProvider { - resourceUrlBlacklist(blacklist: any[]): void; - resourceUrlWhitelist(whitelist: any[]): void; resourceUrlBlacklist(): any[]; + resourceUrlBlacklist(blacklist: any[]): void; resourceUrlWhitelist(): any[]; + resourceUrlWhitelist(whitelist: any[]): void; } /** @@ -1936,33 +1937,33 @@ declare namespace angular { annotate(fn: Function, strictDi?: boolean): string[]; annotate(inlineAnnotatedFunction: any[]): string[]; get(name: string, caller?: string): T; - get(name: '$anchorScroll'): IAnchorScrollService - get(name: '$cacheFactory'): ICacheFactoryService - get(name: '$compile'): ICompileService - get(name: '$controller'): IControllerService - get(name: '$document'): IDocumentService - get(name: '$exceptionHandler'): IExceptionHandlerService - get(name: '$filter'): IFilterService - get(name: '$http'): IHttpService - get(name: '$httpBackend'): IHttpBackendService - get(name: '$httpParamSerializer'): IHttpParamSerializer - get(name: '$httpParamSerializerJQLike'): IHttpParamSerializer - get(name: '$interpolate'): IInterpolateService - get(name: '$interval'): IIntervalService - get(name: '$locale'): ILocaleService - get(name: '$location'): ILocationService - get(name: '$log'): ILogService - get(name: '$parse'): IParseService - get(name: '$q'): IQService - get(name: '$rootElement'): IRootElementService - get(name: '$rootScope'): IRootScopeService - get(name: '$sce'): ISCEService - get(name: '$sceDelegate'): ISCEDelegateService - get(name: '$templateCache'): ITemplateCacheService - get(name: '$templateRequest'): ITemplateRequestService - get(name: '$timeout'): ITimeoutService - get(name: '$window'): IWindowService - get(name: '$xhrFactory'): IXhrFactory + get(name: '$anchorScroll'): IAnchorScrollService; + get(name: '$cacheFactory'): ICacheFactoryService; + get(name: '$compile'): ICompileService; + get(name: '$controller'): IControllerService; + get(name: '$document'): IDocumentService; + get(name: '$exceptionHandler'): IExceptionHandlerService; + get(name: '$filter'): IFilterService; + get(name: '$http'): IHttpService; + get(name: '$httpBackend'): IHttpBackendService; + get(name: '$httpParamSerializer'): IHttpParamSerializer; + get(name: '$httpParamSerializerJQLike'): IHttpParamSerializer; + get(name: '$interpolate'): IInterpolateService; + get(name: '$interval'): IIntervalService; + get(name: '$locale'): ILocaleService; + get(name: '$location'): ILocationService; + get(name: '$log'): ILogService; + get(name: '$parse'): IParseService; + get(name: '$q'): IQService; + get(name: '$rootElement'): IRootElementService; + get(name: '$rootScope'): IRootScopeService; + get(name: '$sce'): ISCEService; + get(name: '$sceDelegate'): ISCEDelegateService; + get(name: '$templateCache'): ITemplateCacheService; + get(name: '$templateRequest'): ITemplateRequestService; + get(name: '$timeout'): ITimeoutService; + get(name: '$window'): IWindowService; + get(name: '$xhrFactory'): IXhrFactory; has(name: string): boolean; instantiate(typeConstructor: Function, locals?: any): T; invoke(inlineAnnotatedFunction: any[]): any; diff --git a/angular/tslint.json b/angular/tslint.json new file mode 100644 index 0000000000..75f86620b4 --- /dev/null +++ b/angular/tslint.json @@ -0,0 +1,20 @@ +{ + "extends": "../tslint.json", + "rules": { + "class-name": true, + "curly": true, + "no-consecutive-blank-lines": true, + "no-shadowed-variable": true, + "quotemark": [true, "single"], + "align": true, + "callable-types": false, + "forbidden-types": false, + "indent": [true, "spaces"], + "interface-name": false, + "linebreak-style": [true, "LF"], + "no-empty-interface": false, + "unified-signatures": false, + "variable-name": [true, "check-format"], + "void-return": false + } +}