From de18da2a0d43cc7c6a4096b2a2d2cb780b2f034b Mon Sep 17 00:00:00 2001 From: Alex Eagle Date: Tue, 7 Jul 2015 20:03:00 -0700 Subject: [PATCH] feat(build): require parameter types Fixes #2833 --- gulpfile.js | 6 ++- .../change_detection/change_detection_util.ts | 1 + .../src/change_detection/parser/ast.ts | 52 ++++++++++--------- .../src/change_detection/parser/locals.ts | 2 +- .../src/change_detection/parser/parser.ts | 2 +- .../src/change_detection/pipes/date_pipe.ts | 4 +- .../pipes/iterable_changes.ts | 14 ++--- .../src/change_detection/pipes/json_pipe.ts | 2 +- .../pipes/keyvalue_changes.ts | 10 ++-- .../change_detection/pipes/limit_to_pipe.ts | 8 +-- .../change_detection/pipes/lowercase_pipe.ts | 4 +- .../src/change_detection/pipes/null_pipe.ts | 8 +-- .../src/change_detection/pipes/number_pipe.ts | 8 +-- .../change_detection/pipes/observable_pipe.ts | 4 +- .../src/change_detection/pipes/pipe.ts | 2 +- .../src/change_detection/pipes/pipes.ts | 6 +-- .../change_detection/pipes/promise_pipe.ts | 4 +- .../change_detection/pipes/uppercase_pipe.ts | 4 +- .../src/core/compiler/element_injector.ts | 6 +-- modules/angular2/src/core/compiler/view.ts | 4 +- .../angular2/src/core/exception_handler.ts | 4 +- .../src/core/testability/get_testability.ts | 4 +- .../src/core/testability/testability.ts | 6 +-- modules/angular2/src/core/zone/ng_zone.ts | 4 +- modules/angular2/src/debug/debug_element.ts | 12 ++--- modules/angular2/src/di/binding.ts | 6 +-- modules/angular2/src/di/exceptions.ts | 2 +- modules/angular2/src/di/injector.ts | 4 +- modules/angular2/src/di/key.ts | 2 +- modules/angular2/src/dom/browser_adapter.ts | 1 + modules/angular2/src/dom/dom_adapter.ts | 1 + .../src/dom/generic_browser_adapter.ts | 4 +- modules/angular2/src/dom/parse5_adapter.ts | 3 +- modules/angular2/src/facade/async.ts | 20 +++---- modules/angular2/src/facade/collection.ts | 46 ++++++++-------- modules/angular2/src/facade/lang.ts | 49 +++++++++-------- .../directives/checkbox_value_accessor.ts | 6 +-- .../directives/default_value_accessor.ts | 6 +-- .../src/forms/directives/ng_form_control.ts | 2 +- .../angular2/src/forms/directives/ng_model.ts | 2 +- .../select_control_value_accessor.ts | 6 +-- modules/angular2/src/forms/model.ts | 4 +- .../src/http/backends/mock_backend.ts | 10 ++-- modules/angular2/src/http/headers.ts | 2 +- .../angular2/src/http/url_search_params.ts | 2 +- modules/angular2/src/mock/location_mock.ts | 7 +-- .../src/mock/mock_location_strategy.ts | 4 +- modules/angular2/src/mock/ng_zone_mock.ts | 4 +- .../src/reflection/reflection_capabilities.ts | 18 ++++--- modules/angular2/src/reflection/reflector.ts | 6 +-- .../render/dom/compiler/compile_control.ts | 2 +- .../render/dom/compiler/compile_pipeline.ts | 2 +- .../src/render/dom/compiler/compiler.ts | 1 + .../src/render/dom/compiler/selector.ts | 4 +- .../dom/compiler/text_interpolation_parser.ts | 9 ++-- .../src/render/dom/events/event_manager.ts | 19 ++++--- .../src/render/dom/events/hammer_gestures.ts | 3 +- .../src/render/dom/events/key_events.ts | 10 ++-- .../emulated_scoped_shadow_dom_strategy.ts | 4 +- .../emulated_unscoped_shadow_dom_strategy.ts | 2 +- .../src/render/dom/shadow_dom/shadow_css.ts | 2 +- .../dom/shadow_dom/shadow_dom_strategy.ts | 5 +- .../src/render/dom/view/proto_view_builder.ts | 22 ++++---- modules/angular2/src/render/dom/view/view.ts | 2 +- modules/angular2/src/router/location.ts | 3 +- .../angular2/src/router/location_strategy.ts | 2 +- modules/angular2/src/router/route_registry.ts | 8 +-- modules/angular2/src/router/router.ts | 6 ++- modules/angular2/src/test_lib/utils.ts | 4 +- .../src/web-workers/shared/serializer.ts | 16 +++--- .../pipes/iterable_changes_spec.ts | 2 +- .../core/compiler/proto_view_factory_spec.ts | 27 ++++++---- modules/angular2/test/di/injector_spec.ts | 2 +- .../test/http/backends/jsonp_backend_spec.ts | 6 ++- .../test/http/backends/xhr_backend_spec.ts | 4 +- modules/angular2/test/http/http_spec.ts | 27 +++++----- .../dom/compiler/directive_parser_spec.ts | 14 ++--- modules/angular2/test/router/outlet_spec.ts | 16 +++--- modules/benchpress/test/runner_spec.ts | 2 +- tools/tslint/requireParameterTypeRule.ts | 38 ++++++++++++++ tools/tslint/requireReturnTypeRule.ts | 7 ++- 81 files changed, 379 insertions(+), 290 deletions(-) create mode 100644 tools/tslint/requireParameterTypeRule.ts diff --git a/gulpfile.js b/gulpfile.js index 0ce6f62a5d..bbb60ef957 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -275,17 +275,19 @@ gulp.task('enforce-format', function() { }); gulp.task('lint', ['build.tools'], function() { + // Built-in rules are at // https://github.com/palantir/tslint#supported-rules var tslintConfig = { "rules": { "semicolon": true, - "requireReturnType": true + "requireReturnType": true, + "requireParameterType": true } }; return gulp.src(['modules/angular2/src/**/*.ts', '!modules/angular2/src/test_lib/**']) .pipe(tslint({configuration: tslintConfig, rulesDirectory: 'dist/tools/tslint'})) - .pipe(tslint.report('prose')); + .pipe(tslint.report('prose', {emitError: true})); }); // ------------ diff --git a/modules/angular2/src/change_detection/change_detection_util.ts b/modules/angular2/src/change_detection/change_detection_util.ts index b55c235c3a..8edb89c0b5 100644 --- a/modules/angular2/src/change_detection/change_detection_util.ts +++ b/modules/angular2/src/change_detection/change_detection_util.ts @@ -45,6 +45,7 @@ function _simpleChange(previousValue, currentValue): SimpleChange { return s; } +/* tslint:disable:requireParameterType */ export class ChangeDetectionUtil { static uninitialized(): Object { return uninitialized; } diff --git a/modules/angular2/src/change_detection/parser/ast.ts b/modules/angular2/src/change_detection/parser/ast.ts index 32ffe6062a..0cfee7cdd3 100644 --- a/modules/angular2/src/change_detection/parser/ast.ts +++ b/modules/angular2/src/change_detection/parser/ast.ts @@ -3,11 +3,11 @@ import {List, Map, ListWrapper, StringMapWrapper} from "angular2/src/facade/coll import {Locals} from "./locals"; export class AST { - eval(context, locals: Locals) { throw new BaseException("Not supported"); } + eval(context: any, locals: Locals): any { throw new BaseException("Not supported"); } get isAssignable(): boolean { return false; } - assign(context, locals: Locals, value) { throw new BaseException("Not supported"); } + assign(context: any, locals: Locals, value: any) { throw new BaseException("Not supported"); } visit(visitor: AstVisitor): any { return null; } @@ -15,7 +15,7 @@ export class AST { } export class EmptyExpr extends AST { - eval(context, locals: Locals): any { return null; } + eval(context: any, locals: Locals): any { return null; } visit(visitor: AstVisitor) { // do nothing @@ -23,7 +23,7 @@ export class EmptyExpr extends AST { } export class ImplicitReceiver extends AST { - eval(context, locals: Locals): any { return context; } + eval(context: any, locals: Locals): any { return context; } visit(visitor: AstVisitor): any { return visitor.visitImplicitReceiver(this); } } @@ -34,7 +34,7 @@ export class ImplicitReceiver extends AST { export class Chain extends AST { constructor(public expressions: List) { super(); } - eval(context, locals: Locals): any { + eval(context: any, locals: Locals): any { var result; for (var i = 0; i < this.expressions.length; i++) { var last = this.expressions[i].eval(context, locals); @@ -49,7 +49,7 @@ export class Chain extends AST { export class Conditional extends AST { constructor(public condition: AST, public trueExp: AST, public falseExp: AST) { super(); } - eval(context, locals: Locals): any { + eval(context: any, locals: Locals): any { if (this.condition.eval(context, locals)) { return this.trueExp.eval(context, locals); } else { @@ -63,7 +63,7 @@ export class Conditional extends AST { export class If extends AST { constructor(public condition: AST, public trueExp: AST, public falseExp?: AST) { super(); } - eval(context, locals) { + eval(context: any, locals: Locals) { if (this.condition.eval(context, locals)) { this.trueExp.eval(context, locals); } else if (isPresent(this.falseExp)) { @@ -80,7 +80,7 @@ export class AccessMember extends AST { super(); } - eval(context, locals: Locals): any { + eval(context: any, locals: Locals): any { if (this.receiver instanceof ImplicitReceiver && isPresent(locals) && locals.contains(this.name)) { return locals.get(this.name); @@ -92,7 +92,7 @@ export class AccessMember extends AST { get isAssignable(): boolean { return true; } - assign(context, locals: Locals, value): any { + assign(context: any, locals: Locals, value: any): any { var evaluatedContext = this.receiver.eval(context, locals); if (this.receiver instanceof ImplicitReceiver && isPresent(locals) && @@ -112,7 +112,7 @@ export class SafeAccessMember extends AST { super(); } - eval(context, locals: Locals): any { + eval(context: any, locals: Locals): any { var evaluatedReceiver = this.receiver.eval(context, locals); return isBlank(evaluatedReceiver) ? null : this.getter(evaluatedReceiver); } @@ -123,7 +123,7 @@ export class SafeAccessMember extends AST { export class KeyedAccess extends AST { constructor(public obj: AST, public key: AST) { super(); } - eval(context, locals: Locals): any { + eval(context: any, locals: Locals): any { var obj: any = this.obj.eval(context, locals); var key: any = this.key.eval(context, locals); return obj[key]; @@ -131,7 +131,7 @@ export class KeyedAccess extends AST { get isAssignable(): boolean { return true; } - assign(context, locals: Locals, value): any { + assign(context: any, locals: Locals, value: any): any { var obj: any = this.obj.eval(context, locals); var key: any = this.key.eval(context, locals); obj[key] = value; @@ -150,7 +150,7 @@ export class BindingPipe extends AST { export class LiteralPrimitive extends AST { constructor(public value) { super(); } - eval(context, locals: Locals): any { return this.value; } + eval(context: any, locals: Locals): any { return this.value; } visit(visitor: AstVisitor): any { return visitor.visitLiteralPrimitive(this); } } @@ -158,7 +158,7 @@ export class LiteralPrimitive extends AST { export class LiteralArray extends AST { constructor(public expressions: List) { super(); } - eval(context, locals: Locals): any { + eval(context: any, locals: Locals): any { return ListWrapper.map(this.expressions, (e) => e.eval(context, locals)); } @@ -168,7 +168,7 @@ export class LiteralArray extends AST { export class LiteralMap extends AST { constructor(public keys: List, public values: List) { super(); } - eval(context, locals: Locals): any { + eval(context: any, locals: Locals): any { var res = StringMapWrapper.create(); for (var i = 0; i < this.keys.length; ++i) { StringMapWrapper.set(res, this.keys[i], this.values[i].eval(context, locals)); @@ -182,7 +182,7 @@ export class LiteralMap extends AST { export class Interpolation extends AST { constructor(public strings: List, public expressions: List) { super(); } - eval(context, locals): any { + eval(context: any, locals: Locals): any { throw new BaseException("evaluating an Interpolation is not supported"); } @@ -192,7 +192,7 @@ export class Interpolation extends AST { export class Binary extends AST { constructor(public operation: string, public left: AST, public right: AST) { super(); } - eval(context, locals: Locals): any { + eval(context: any, locals: Locals): any { var left: any = this.left.eval(context, locals); switch (this.operation) { case '&&': @@ -243,15 +243,15 @@ export class Binary extends AST { export class PrefixNot extends AST { constructor(public expression: AST) { super(); } - eval(context, locals: Locals): any { return !this.expression.eval(context, locals); } + eval(context: any, locals: Locals): any { return !this.expression.eval(context, locals); } visit(visitor: AstVisitor): any { return visitor.visitPrefixNot(this); } } export class Assignment extends AST { - constructor(public target: AST, public value: AST) { super(); } + constructor(public target: AST, public value: any) { super(); } - eval(context, locals: Locals): any { + eval(context: any, locals: Locals): any { return this.target.assign(context, locals, this.value.eval(context, locals)); } @@ -264,7 +264,7 @@ export class MethodCall extends AST { super(); } - eval(context, locals: Locals): any { + eval(context: any, locals: Locals): any { var evaluatedArgs = evalList(context, locals, this.args); if (this.receiver instanceof ImplicitReceiver && isPresent(locals) && locals.contains(this.name)) { @@ -285,7 +285,7 @@ export class SafeMethodCall extends AST { super(); } - eval(context, locals: Locals): any { + eval(context: any, locals: Locals): any { var evaluatedReceiver = this.receiver.eval(context, locals); if (isBlank(evaluatedReceiver)) return null; var evaluatedArgs = evalList(context, locals, this.args); @@ -298,7 +298,7 @@ export class SafeMethodCall extends AST { export class FunctionCall extends AST { constructor(public target: AST, public args: List) { super(); } - eval(context, locals: Locals): any { + eval(context: any, locals: Locals): any { var obj: any = this.target.eval(context, locals); if (!(obj instanceof Function)) { throw new BaseException(`${obj} is not a function`); @@ -312,11 +312,13 @@ export class FunctionCall extends AST { export class ASTWithSource extends AST { constructor(public ast: AST, public source: string, public location: string) { super(); } - eval(context, locals: Locals): any { return this.ast.eval(context, locals); } + eval(context: any, locals: Locals): any { return this.ast.eval(context, locals); } get isAssignable(): boolean { return this.ast.isAssignable; } - assign(context, locals: Locals, value): any { return this.ast.assign(context, locals, value); } + assign(context: any, locals: Locals, value: any): any { + return this.ast.assign(context, locals, value); + } visit(visitor: AstVisitor): any { return this.ast.visit(visitor); } diff --git a/modules/angular2/src/change_detection/parser/locals.ts b/modules/angular2/src/change_detection/parser/locals.ts index 5042991d85..349e0fa57e 100644 --- a/modules/angular2/src/change_detection/parser/locals.ts +++ b/modules/angular2/src/change_detection/parser/locals.ts @@ -28,7 +28,7 @@ export class Locals { throw new BaseException(`Cannot find '${name}'`); } - set(name: string, value): void { + set(name: string, value: any): void { // TODO(rado): consider removing this check if we can guarantee this is not // exposed to the public API. // TODO: vsavkin maybe it should check only the local map diff --git a/modules/angular2/src/change_detection/parser/parser.ts b/modules/angular2/src/change_detection/parser/parser.ts index 847195a28c..4624d5fbcf 100644 --- a/modules/angular2/src/change_detection/parser/parser.ts +++ b/modules/angular2/src/change_detection/parser/parser.ts @@ -479,7 +479,7 @@ class _ParseAST { return new LiteralMap(keys, values); } - parseAccessMemberOrMethodCall(receiver, isSafe: boolean = false): AST { + parseAccessMemberOrMethodCall(receiver: AST, isSafe: boolean = false): AST { let id = this.expectIdentifierOrKeyword(); if (this.optionalCharacter($LPAREN)) { diff --git a/modules/angular2/src/change_detection/pipes/date_pipe.ts b/modules/angular2/src/change_detection/pipes/date_pipe.ts index 07aea630de..5dde144c70 100644 --- a/modules/angular2/src/change_detection/pipes/date_pipe.ts +++ b/modules/angular2/src/change_detection/pipes/date_pipe.ts @@ -83,7 +83,7 @@ export class DatePipe extends BasePipe implements PipeFactory { }; - transform(value, args: List): string { + transform(value: any, args: List): string { var pattern: string = isPresent(args) && args.length > 0 ? args[0] : 'mediumDate'; if (isNumber(value)) { value = DateWrapper.fromMillis(value); @@ -94,7 +94,7 @@ export class DatePipe extends BasePipe implements PipeFactory { return DateFormatter.format(value, defaultLocale, pattern); } - supports(obj): boolean { return isDate(obj) || isNumber(obj); } + supports(obj: any): boolean { return isDate(obj) || isNumber(obj); } create(cdRef: ChangeDetectorRef): Pipe { return this; } } diff --git a/modules/angular2/src/change_detection/pipes/iterable_changes.ts b/modules/angular2/src/change_detection/pipes/iterable_changes.ts index c480db4aa9..22a5e4717e 100644 --- a/modules/angular2/src/change_detection/pipes/iterable_changes.ts +++ b/modules/angular2/src/change_detection/pipes/iterable_changes.ts @@ -20,7 +20,7 @@ import {ChangeDetectorRef} from '../change_detector_ref'; @CONST() export class IterableChangesFactory implements PipeFactory { - supports(obj): boolean { return IterableChanges.supportsObj(obj); } + supports(obj: any): boolean { return IterableChanges.supportsObj(obj); } create(cdRef: ChangeDetectorRef): Pipe { return new IterableChanges(); } } @@ -44,9 +44,9 @@ export class IterableChanges extends BasePipe { constructor() { super(); } - static supportsObj(obj): boolean { return isListLikeIterable(obj); } + static supportsObj(obj: Object): boolean { return isListLikeIterable(obj); } - supports(obj): boolean { return IterableChanges.supportsObj(obj); } + supports(obj: Object): boolean { return IterableChanges.supportsObj(obj); } get collection() { return this._collection; } @@ -87,7 +87,7 @@ export class IterableChanges extends BasePipe { } } - transform(collection, args: List = null): any { + transform(collection: any, args: List = null): any { if (this.check(collection)) { return WrappedValue.wrap(this); } else { @@ -96,7 +96,7 @@ export class IterableChanges extends BasePipe { } // todo(vicb): optim for UnmodifiableListView (frozen arrays) - check(collection): boolean { + check(collection: any): boolean { this._reset(); var record: CollectionChangeRecord = this._itHead; @@ -524,7 +524,7 @@ class _DuplicateItemRecordList { // Returns a CollectionChangeRecord having CollectionChangeRecord.item == item and // CollectionChangeRecord.currentIndex >= afterIndex - get(item, afterIndex: int): CollectionChangeRecord { + get(item: any, afterIndex: int): CollectionChangeRecord { var record: CollectionChangeRecord; for (record = this._head; record !== null; record = record._nextDup) { if ((afterIndex === null || afterIndex < record.currentIndex) && @@ -588,7 +588,7 @@ class _DuplicateMap { * Use case: `[a, b, c, a, a]` if we are at index `3` which is the second `a` then asking if we * have any more `a`s needs to return the last `a` not the first or second. */ - get(value, afterIndex = null): CollectionChangeRecord { + get(value: any, afterIndex: int = null): CollectionChangeRecord { var key = getMapKey(value); var recordList = this.map.get(key); diff --git a/modules/angular2/src/change_detection/pipes/json_pipe.ts b/modules/angular2/src/change_detection/pipes/json_pipe.ts index e97e6c1f9c..2b6512ce8c 100644 --- a/modules/angular2/src/change_detection/pipes/json_pipe.ts +++ b/modules/angular2/src/change_detection/pipes/json_pipe.ts @@ -27,7 +27,7 @@ import {ChangeDetectorRef} from '../change_detector_ref'; */ @CONST() export class JsonPipe extends BasePipe implements PipeFactory { - transform(value, args: List = null): string { return Json.stringify(value); } + transform(value: any, args: List = null): string { return Json.stringify(value); } create(cdRef: ChangeDetectorRef): Pipe { return this; } } diff --git a/modules/angular2/src/change_detection/pipes/keyvalue_changes.ts b/modules/angular2/src/change_detection/pipes/keyvalue_changes.ts index 0c527cb77f..9fa998b381 100644 --- a/modules/angular2/src/change_detection/pipes/keyvalue_changes.ts +++ b/modules/angular2/src/change_detection/pipes/keyvalue_changes.ts @@ -5,7 +5,7 @@ import {WrappedValue, BasePipe, Pipe, PipeFactory} from './pipe'; @CONST() export class KeyValueChangesFactory implements PipeFactory { - supports(obj): boolean { return KeyValueChanges.supportsObj(obj); } + supports(obj: any): boolean { return KeyValueChanges.supportsObj(obj); } create(cdRef: ChangeDetectorRef): Pipe { return new KeyValueChanges(); } } @@ -21,11 +21,11 @@ export class KeyValueChanges extends BasePipe { private _removalsHead: KVChangeRecord = null; private _removalsTail: KVChangeRecord = null; - static supportsObj(obj): boolean { return obj instanceof Map || isJsObject(obj); } + static supportsObj(obj: any): boolean { return obj instanceof Map || isJsObject(obj); } - supports(obj): boolean { return KeyValueChanges.supportsObj(obj); } + supports(obj: any): boolean { return KeyValueChanges.supportsObj(obj); } - transform(map, args: List = null): any { + transform(map: Map, args: List = null): any { if (this.check(map)) { return WrappedValue.wrap(this); } else { @@ -73,7 +73,7 @@ export class KeyValueChanges extends BasePipe { } } - check(map): boolean { + check(map: Map): boolean { this._reset(); var records = this._records; var oldSeqRecord: KVChangeRecord = this._mapHead; diff --git a/modules/angular2/src/change_detection/pipes/limit_to_pipe.ts b/modules/angular2/src/change_detection/pipes/limit_to_pipe.ts index de40bc800a..c7e296dc74 100644 --- a/modules/angular2/src/change_detection/pipes/limit_to_pipe.ts +++ b/modules/angular2/src/change_detection/pipes/limit_to_pipe.ts @@ -51,11 +51,11 @@ import {ChangeDetectorRef} from '../change_detector_ref'; * {{ 'abcdefghij' | limitTo: -100 }} // output is 'abcdefghij' */ export class LimitToPipe implements Pipe { - static supportsObj(obj): boolean { return isString(obj) || isArray(obj); } + static supportsObj(obj: any): boolean { return isString(obj) || isArray(obj); } - supports(obj): boolean { return LimitToPipe.supportsObj(obj); } + supports(obj: any): boolean { return LimitToPipe.supportsObj(obj); } - transform(value, args: List = null): any { + transform(value: any, args: List = null): any { if (isBlank(args) || args.length == 0) { throw new BaseException('limitTo pipe requires one argument'); } @@ -76,7 +76,7 @@ export class LimitToPipe implements Pipe { @CONST() export class LimitToPipeFactory implements PipeFactory { - supports(obj): boolean { return LimitToPipe.supportsObj(obj); } + supports(obj: any): boolean { return LimitToPipe.supportsObj(obj); } create(cdRef: ChangeDetectorRef): Pipe { return new LimitToPipe(); } } diff --git a/modules/angular2/src/change_detection/pipes/lowercase_pipe.ts b/modules/angular2/src/change_detection/pipes/lowercase_pipe.ts index 21abbcbde8..51fb7d18c3 100644 --- a/modules/angular2/src/change_detection/pipes/lowercase_pipe.ts +++ b/modules/angular2/src/change_detection/pipes/lowercase_pipe.ts @@ -25,7 +25,7 @@ import {ChangeDetectorRef} from '../change_detector_ref'; export class LowerCasePipe implements Pipe { _latestValue: string = null; - supports(str): boolean { return isString(str); } + supports(str: any): boolean { return isString(str); } onDestroy(): void { this._latestValue = null; } @@ -41,7 +41,7 @@ export class LowerCasePipe implements Pipe { @CONST() export class LowerCaseFactory implements PipeFactory { - supports(str): boolean { return isString(str); } + supports(str: any): boolean { return isString(str); } create(cdRef: ChangeDetectorRef): Pipe { return new LowerCasePipe(); } } diff --git a/modules/angular2/src/change_detection/pipes/null_pipe.ts b/modules/angular2/src/change_detection/pipes/null_pipe.ts index 33a72e5c97..93492424ad 100644 --- a/modules/angular2/src/change_detection/pipes/null_pipe.ts +++ b/modules/angular2/src/change_detection/pipes/null_pipe.ts @@ -4,7 +4,7 @@ import {ChangeDetectorRef} from '../change_detector_ref'; @CONST() export class NullPipeFactory implements PipeFactory { - supports(obj): boolean { return NullPipe.supportsObj(obj); } + supports(obj: any): boolean { return NullPipe.supportsObj(obj); } create(cdRef: ChangeDetectorRef): Pipe { return new NullPipe(); } } @@ -12,11 +12,11 @@ export class NullPipeFactory implements PipeFactory { export class NullPipe extends BasePipe { called: boolean = false; - static supportsObj(obj): boolean { return isBlank(obj); } + static supportsObj(obj: any): boolean { return isBlank(obj); } - supports(obj): boolean { return NullPipe.supportsObj(obj); } + supports(obj: any): boolean { return NullPipe.supportsObj(obj); } - transform(value, args: List = null): WrappedValue { + transform(value: any, args: List = null): WrappedValue { if (!this.called) { this.called = true; return WrappedValue.wrap(null); diff --git a/modules/angular2/src/change_detection/pipes/number_pipe.ts b/modules/angular2/src/change_detection/pipes/number_pipe.ts index d3aaf01216..1663a70e4a 100644 --- a/modules/angular2/src/change_detection/pipes/number_pipe.ts +++ b/modules/angular2/src/change_detection/pipes/number_pipe.ts @@ -46,7 +46,7 @@ export class NumberPipe extends BasePipe implements PipeFactory { }); } - supports(obj): boolean { return isNumber(obj); } + supports(obj: any): boolean { return isNumber(obj); } create(cdRef: ChangeDetectorRef): Pipe { return this; } } @@ -78,7 +78,7 @@ export class NumberPipe extends BasePipe implements PipeFactory { */ @CONST() export class DecimalPipe extends NumberPipe { - transform(value, args: any[]): string { + transform(value: any, args: any[]): string { var digits: string = ListWrapper.first(args); return NumberPipe._format(value, NumberFormatStyle.DECIMAL, digits); } @@ -95,7 +95,7 @@ export class DecimalPipe extends NumberPipe { */ @CONST() export class PercentPipe extends NumberPipe { - transform(value, args: any[]): string { + transform(value: any, args: any[]): string { var digits: string = ListWrapper.first(args); return NumberPipe._format(value, NumberFormatStyle.PERCENT, digits); } @@ -116,7 +116,7 @@ export class PercentPipe extends NumberPipe { */ @CONST() export class CurrencyPipe extends NumberPipe { - transform(value, args: any[]): string { + transform(value: any, args: any[]): string { var currencyCode: string = isPresent(args) && args.length > 0 ? args[0] : 'USD'; var symbolDisplay: boolean = isPresent(args) && args.length > 1 ? args[1] : false; var digits: string = isPresent(args) && args.length > 2 ? args[2] : null; diff --git a/modules/angular2/src/change_detection/pipes/observable_pipe.ts b/modules/angular2/src/change_detection/pipes/observable_pipe.ts index 4e7b57c389..7abfc5deee 100644 --- a/modules/angular2/src/change_detection/pipes/observable_pipe.ts +++ b/modules/angular2/src/change_detection/pipes/observable_pipe.ts @@ -36,7 +36,7 @@ export class ObservablePipe implements Pipe { constructor(public _ref: ChangeDetectorRef) {} - supports(obs): boolean { return ObservableWrapper.isObservable(obs); } + supports(obs: any): boolean { return ObservableWrapper.isObservable(obs); } onDestroy(): void { if (isPresent(this._subscription)) { @@ -88,7 +88,7 @@ export class ObservablePipe implements Pipe { */ @CONST() export class ObservablePipeFactory implements PipeFactory { - supports(obs): boolean { return ObservableWrapper.isObservable(obs); } + supports(obs: any): boolean { return ObservableWrapper.isObservable(obs); } create(cdRef: ChangeDetectorRef): Pipe { return new ObservablePipe(cdRef); } } diff --git a/modules/angular2/src/change_detection/pipes/pipe.ts b/modules/angular2/src/change_detection/pipes/pipe.ts index bdb9388198..e73378b4d7 100644 --- a/modules/angular2/src/change_detection/pipes/pipe.ts +++ b/modules/angular2/src/change_detection/pipes/pipe.ts @@ -69,7 +69,7 @@ export interface Pipe { */ @CONST() export class BasePipe implements Pipe { - supports(obj): boolean { return true; } + supports(obj: any): boolean { return true; } onDestroy(): void {} transform(value: any, args: List): any { return _abstract(); } } diff --git a/modules/angular2/src/change_detection/pipes/pipes.ts b/modules/angular2/src/change_detection/pipes/pipes.ts index 32cacaf843..152321f3ae 100644 --- a/modules/angular2/src/change_detection/pipes/pipes.ts +++ b/modules/angular2/src/change_detection/pipes/pipes.ts @@ -28,7 +28,7 @@ export class Pipes { config: StringMap; constructor(config: StringMap) { this.config = config; } - get(type: string, obj, cdRef?: ChangeDetectorRef, existingPipe?: Pipe): Pipe { + get(type: string, obj: any, cdRef?: ChangeDetectorRef, existingPipe?: Pipe): Pipe { if (isPresent(existingPipe) && existingPipe.supports(obj)) return existingPipe; if (isPresent(existingPipe)) existingPipe.onDestroy(); @@ -67,7 +67,7 @@ export class Pipes { * }) * ``` */ - static extend(config): Binding { + static extend(config: StringMap): Binding { return new Binding(Pipes, { toFactory: (pipes: Pipes) => { if (isBlank(pipes)) { @@ -82,7 +82,7 @@ export class Pipes { }); } - static create(config, pipes: Pipes = null): Pipes { + static create(config: StringMap, pipes: Pipes = null): Pipes { if (isPresent(pipes)) { StringMapWrapper.forEach(pipes.config, (v: PipeFactory[], k: string) => { if (StringMapWrapper.contains(config, k)) { diff --git a/modules/angular2/src/change_detection/pipes/promise_pipe.ts b/modules/angular2/src/change_detection/pipes/promise_pipe.ts index d27557e044..4b8b00a8bc 100644 --- a/modules/angular2/src/change_detection/pipes/promise_pipe.ts +++ b/modules/angular2/src/change_detection/pipes/promise_pipe.ts @@ -33,7 +33,7 @@ export class PromisePipe implements Pipe { constructor(public _ref: ChangeDetectorRef) {} - supports(promise): boolean { return isPromise(promise); } + supports(promise: any): boolean { return isPromise(promise); } onDestroy(): void { if (isPresent(this._sourcePromise)) { @@ -78,7 +78,7 @@ export class PromisePipe implements Pipe { */ @CONST() export class PromisePipeFactory implements PipeFactory { - supports(promise): boolean { return isPromise(promise); } + supports(promise: any): boolean { return isPromise(promise); } create(cdRef: ChangeDetectorRef): Pipe { return new PromisePipe(cdRef); } } diff --git a/modules/angular2/src/change_detection/pipes/uppercase_pipe.ts b/modules/angular2/src/change_detection/pipes/uppercase_pipe.ts index d238a08db8..56cb8fb509 100644 --- a/modules/angular2/src/change_detection/pipes/uppercase_pipe.ts +++ b/modules/angular2/src/change_detection/pipes/uppercase_pipe.ts @@ -25,7 +25,7 @@ import {ChangeDetectorRef} from '../change_detector_ref'; export class UpperCasePipe implements Pipe { _latestValue: string = null; - supports(str): boolean { return isString(str); } + supports(str: any): boolean { return isString(str); } onDestroy(): void { this._latestValue = null; } @@ -41,7 +41,7 @@ export class UpperCasePipe implements Pipe { @CONST() export class UpperCaseFactory implements PipeFactory { - supports(str): boolean { return isString(str); } + supports(str: any): boolean { return isString(str); } create(cdRef: ChangeDetectorRef): Pipe { return new UpperCasePipe(); } } diff --git a/modules/angular2/src/core/compiler/element_injector.ts b/modules/angular2/src/core/compiler/element_injector.ts index 2092a1a534..8b9451be71 100644 --- a/modules/angular2/src/core/compiler/element_injector.ts +++ b/modules/angular2/src/core/compiler/element_injector.ts @@ -286,7 +286,7 @@ export class EventEmitterAccessor { subscribe(view: viewModule.AppView, boundElementIndex: number, directive: Object): Object { var eventEmitter = this.getter(directive); - return ObservableWrapper.subscribe( + return ObservableWrapper.subscribe( eventEmitter, eventObj => view.triggerEventHandlers(this.eventName, eventObj, boundElementIndex)); } @@ -297,7 +297,7 @@ export class HostActionAccessor { subscribe(view: viewModule.AppView, boundElementIndex: number, directive: Object): Object { var eventEmitter = this.getter(directive); - return ObservableWrapper.subscribe( + return ObservableWrapper.subscribe>( eventEmitter, actionArgs => view.invokeElementMethod(boundElementIndex, this.methodName, actionArgs)); } @@ -542,7 +542,7 @@ export class ElementInjector extends TreeNode implements Depend return isPresent(index) ? this.getDirectiveAtIndex(index) : this.getElementRef(); } - get(token): any { return this._injector.get(token); } + get(token: any): any { return this._injector.get(token); } hasDirective(type: Type): boolean { return isPresent(this._injector.getOptional(type)); } diff --git a/modules/angular2/src/core/compiler/view.ts b/modules/angular2/src/core/compiler/view.ts index 82912cb0bf..a07c606e93 100644 --- a/modules/angular2/src/core/compiler/view.ts +++ b/modules/angular2/src/core/compiler/view.ts @@ -135,7 +135,7 @@ export class AppView implements ChangeDispatcher, RenderEventDispatcher { this.viewContainers = viewContainers; } - setLocal(contextName: string, value): void { + setLocal(contextName: string, value: any): void { if (!this.hydrated()) throw new BaseException('Cannot set locals on dehydrated view.'); if (!this.proto.variableBindings.has(contextName)) { return; @@ -155,7 +155,7 @@ export class AppView implements ChangeDispatcher, RenderEventDispatcher { * @param {*} eventObj * @param {int} boundElementIndex */ - triggerEventHandlers(eventName: string, eventObj, boundElementIndex: int): void { + triggerEventHandlers(eventName: string, eventObj: Event, boundElementIndex: int): void { var locals = new Map(); locals.set('$event', eventObj); this.dispatchEvent(boundElementIndex, eventName, locals); diff --git a/modules/angular2/src/core/exception_handler.ts b/modules/angular2/src/core/exception_handler.ts index f1af1ad60e..cb80e47ee6 100644 --- a/modules/angular2/src/core/exception_handler.ts +++ b/modules/angular2/src/core/exception_handler.ts @@ -33,9 +33,9 @@ import {DOM} from 'angular2/src/dom/dom_adapter'; */ @Injectable() export class ExceptionHandler { - call(error, stackTrace = null, reason = null) { + call(error: Object, stackTrace: string | List = null, reason: string = null) { var longStackTrace = - isListLikeIterable(stackTrace) ? ListWrapper.join(stackTrace, "\n\n") : stackTrace; + isListLikeIterable(stackTrace) ? ListWrapper.join(stackTrace, "\n\n") : stackTrace; var reasonStr = isPresent(reason) ? `\n${reason}` : ''; DOM.logError(`${error}${reasonStr}\nSTACKTRACE:\n${longStackTrace}`); } diff --git a/modules/angular2/src/core/testability/get_testability.ts b/modules/angular2/src/core/testability/get_testability.ts index beded01be8..c84c8ff3f8 100644 --- a/modules/angular2/src/core/testability/get_testability.ts +++ b/modules/angular2/src/core/testability/get_testability.ts @@ -8,14 +8,14 @@ class PublicTestability { whenStable(callback: Function) { this._testability.whenStable(callback); } - findBindings(using, binding: string, exactMatch: boolean): List { + findBindings(using: any, binding: string, exactMatch: boolean): List { return this._testability.findBindings(using, binding, exactMatch); } } export class GetTestability { static addToWindow(registry: TestabilityRegistry) { - global.getAngularTestability = function(elem): PublicTestability { + global.getAngularTestability = function(elem: Element): PublicTestability { var testability = registry.findTestabilityInTree(elem); if (testability == null) { diff --git a/modules/angular2/src/core/testability/testability.ts b/modules/angular2/src/core/testability/testability.ts index 5e4921c8de..f3ee2699aa 100644 --- a/modules/angular2/src/core/testability/testability.ts +++ b/modules/angular2/src/core/testability/testability.ts @@ -47,7 +47,7 @@ export class Testability { getPendingCount(): number { return this._pendingCount; } - findBindings(using, binding: string, exactMatch: boolean): List { + findBindings(using: any, binding: string, exactMatch: boolean): List { // TODO(juliemr): implement. return []; } @@ -63,11 +63,11 @@ export class TestabilityRegistry { getTestabilityModule.GetTestability.addToWindow(this); } - registerApplication(token, testability: Testability) { + registerApplication(token: any, testability: Testability) { this._applications.set(token, testability); } - findTestabilityInTree(elem): Testability { + findTestabilityInTree(elem: Node): Testability { if (elem == null) { return null; } diff --git a/modules/angular2/src/core/zone/ng_zone.ts b/modules/angular2/src/core/zone/ng_zone.ts index 458b09f1e7..ef5bcd04af 100644 --- a/modules/angular2/src/core/zone/ng_zone.ts +++ b/modules/angular2/src/core/zone/ng_zone.ts @@ -121,7 +121,7 @@ export class NgZone { * }); * ``` */ - run(fn): any { + run(fn: () => any): any { if (this._disabled) { return fn(); } else { @@ -145,7 +145,7 @@ export class NgZone { * }); * ``` */ - runOutsideAngular(fn): any { + runOutsideAngular(fn: () => any): any { if (this._disabled) { return fn(); } else { diff --git a/modules/angular2/src/debug/debug_element.ts b/modules/angular2/src/debug/debug_element.ts index e8edbdee93..d320dedeb3 100644 --- a/modules/angular2/src/debug/debug_element.ts +++ b/modules/angular2/src/debug/debug_element.ts @@ -65,7 +65,7 @@ export class DebugElement { return this._getChildElements(shadowView, null); } - triggerEventHandler(eventName, eventObj): void { + triggerEventHandler(eventName: string, eventObj: Event): void { this._parentView.triggerEventHandlers(eventName, eventObj, this._boundElementIndex); } @@ -94,7 +94,7 @@ export class DebugElement { * * @return {DebugElement} */ - query(predicate: Predicate, scope = Scope.all): DebugElement { + query(predicate: Predicate, scope: Function = Scope.all): DebugElement { var results = this.queryAll(predicate, scope); return results.length > 0 ? results[0] : null; } @@ -108,7 +108,7 @@ export class DebugElement { * * @return {List} */ - queryAll(predicate: Predicate, scope = Scope.all): List { + queryAll(predicate: Predicate, scope: Function = Scope.all): List { var elementsInScope = scope(this); return ListWrapper.filter(elementsInScope, predicate); @@ -146,7 +146,7 @@ export function asNativeElements(arr: List): List { } export class Scope { - static all(debugElement): List { + static all(debugElement: DebugElement): List { var scope = []; scope.push(debugElement); @@ -158,7 +158,7 @@ export class Scope { return scope; } - static light(debugElement): List { + static light(debugElement: DebugElement): List { var scope = []; ListWrapper.forEach(debugElement.children, (child) => { scope.push(child); @@ -167,7 +167,7 @@ export class Scope { return scope; } - static view(debugElement): List { + static view(debugElement: DebugElement): List { var scope = []; ListWrapper.forEach(debugElement.componentViewChildren, (child) => { diff --git a/modules/angular2/src/di/binding.ts b/modules/angular2/src/di/binding.ts index 3e5a00ce18..0e96ecf6cd 100644 --- a/modules/angular2/src/di/binding.ts +++ b/modules/angular2/src/di/binding.ts @@ -309,13 +309,13 @@ export class BindingBuilder { * expect(injector.get(String)).toEqual('Hello'); * ``` */ - toValue(value): Binding { return new Binding(this.token, {toValue: value}); } + toValue(value: any): Binding { return new Binding(this.token, {toValue: value}); } /** * Binds a key to the alias for an existing key. * * An alias means that we will return the same instance as if the alias token was used. (This is - * in contrast to `toClass` where a separet instance of `toClass` will be returned.) + * in contrast to `toClass` where a separate instance of `toClass` will be returned.) * * ## Example * @@ -344,7 +344,7 @@ export class BindingBuilder { * expect(injectorClass.get(Vehicle) instanceof Car).toBe(true); * ``` */ - toAlias(aliasToken): Binding { + toAlias(aliasToken: /*Type*/ any): Binding { if (isBlank(aliasToken)) { throw new BaseException(`Can not alias ${stringify(this.token)} to a blank value!`); } diff --git a/modules/angular2/src/di/exceptions.ts b/modules/angular2/src/di/exceptions.ts index 07bbd91f90..8dab68887e 100644 --- a/modules/angular2/src/di/exceptions.ts +++ b/modules/angular2/src/di/exceptions.ts @@ -42,7 +42,7 @@ export class AbstractBindingError extends BaseException { } // TODO(tbosch): Can't do key:Key as this results in a circular dependency! - addKey(key): void { + addKey(key: any): void { this.keys.push(key); this.message = this.constructResolvingMessage(this.keys); } diff --git a/modules/angular2/src/di/injector.ts b/modules/angular2/src/di/injector.ts index 394cbdd021..d06980f34e 100644 --- a/modules/angular2/src/di/injector.ts +++ b/modules/angular2/src/di/injector.ts @@ -480,7 +480,7 @@ export class Injector { *binding). * @returns an instance represented by the token. Throws if not found. */ - get(token): any { + get(token: any): any { return this._getByKey(Key.get(token), DEFAULT_VISIBILITY, false, PUBLIC_AND_PRIVATE); } @@ -490,7 +490,7 @@ export class Injector { * @param `token`: usually a `Type`. (Same as the token used while setting up a binding). * @returns an instance represented by the token. Returns `null` if not found. */ - getOptional(token): any { + getOptional(token: any): any { return this._getByKey(Key.get(token), DEFAULT_VISIBILITY, true, PUBLIC_AND_PRIVATE); } diff --git a/modules/angular2/src/di/key.ts b/modules/angular2/src/di/key.ts index 8021d65a40..4e76899259 100644 --- a/modules/angular2/src/di/key.ts +++ b/modules/angular2/src/di/key.ts @@ -30,7 +30,7 @@ export class Key { /** * Retrieves a `Key` for a token. */ - static get(token): Key { return _globalKeyRegistry.get(resolveForwardRef(token)); } + static get(token: Object): Key { return _globalKeyRegistry.get(resolveForwardRef(token)); } /** * @returns the number of keys registered in the system. diff --git a/modules/angular2/src/dom/browser_adapter.ts b/modules/angular2/src/dom/browser_adapter.ts index 2c37db9e48..68ef2f89b3 100644 --- a/modules/angular2/src/dom/browser_adapter.ts +++ b/modules/angular2/src/dom/browser_adapter.ts @@ -48,6 +48,7 @@ var _chromeNumKeyPadMap = { '\x90': 'NumLock' }; +/* tslint:disable:requireParameterType */ export class BrowserDomAdapter extends GenericBrowserDomAdapter { static makeCurrent() { setRootDomAdapter(new BrowserDomAdapter()); } hasProperty(element, name: string): boolean { return name in element; } diff --git a/modules/angular2/src/dom/dom_adapter.ts b/modules/angular2/src/dom/dom_adapter.ts index ea15ab8053..4c9ee25bc6 100644 --- a/modules/angular2/src/dom/dom_adapter.ts +++ b/modules/angular2/src/dom/dom_adapter.ts @@ -12,6 +12,7 @@ function _abstract() { return new BaseException('This method is abstract'); } +/* tslint:disable:requireParameterType */ /** * Provides DOM operations in an environment-agnostic way. */ diff --git a/modules/angular2/src/dom/generic_browser_adapter.ts b/modules/angular2/src/dom/generic_browser_adapter.ts index f7bc35c9fa..759d0fbd3d 100644 --- a/modules/angular2/src/dom/generic_browser_adapter.ts +++ b/modules/angular2/src/dom/generic_browser_adapter.ts @@ -6,8 +6,8 @@ import {DomAdapter} from './dom_adapter'; * Provides DOM operations in any browser environment. */ export class GenericBrowserDomAdapter extends DomAdapter { - getDistributedNodes(el): List { return el.getDistributedNodes(); } - resolveAndSetHref(el, baseUrl: string, href: string) { + getDistributedNodes(el: HTMLElement): List { return (el).getDistributedNodes(); } + resolveAndSetHref(el: HTMLAnchorElement, baseUrl: string, href: string) { el.href = href == null ? baseUrl : baseUrl + '/../' + href; } cssToRules(css: string): List { diff --git a/modules/angular2/src/dom/parse5_adapter.ts b/modules/angular2/src/dom/parse5_adapter.ts index 54c0127d8b..954c49b30c 100644 --- a/modules/angular2/src/dom/parse5_adapter.ts +++ b/modules/angular2/src/dom/parse5_adapter.ts @@ -25,6 +25,7 @@ function _notImplemented(methodName) { return new BaseException('This method is not implemented in Parse5DomAdapter: ' + methodName); } +/* tslint:disable:requireParameterType */ export class Parse5DomAdapter extends DomAdapter { static makeCurrent() { setRootDomAdapter(new Parse5DomAdapter()); } @@ -112,7 +113,7 @@ export class Parse5DomAdapter extends DomAdapter { onAndCancel(el, evt, listener): Function { this.on(el, evt, listener); return () => { - ListWrapper.remove(StringMapWrapper.get(el._eventListenersMap, evt), listener); + ListWrapper.remove(StringMapWrapper.get>(el._eventListenersMap, evt), listener); }; } dispatchEvent(el, evt) { diff --git a/modules/angular2/src/facade/async.ts b/modules/angular2/src/facade/async.ts index cf2832973c..f6ff6ff863 100644 --- a/modules/angular2/src/facade/async.ts +++ b/modules/angular2/src/facade/async.ts @@ -14,9 +14,9 @@ export interface PromiseCompleter { } export class PromiseWrapper { - static resolve(obj): Promise { return Promise.resolve(obj); } + static resolve(obj: T): Promise { return Promise.resolve(obj); } - static reject(obj, _): Promise { return Promise.reject(obj); } + static reject(obj: any, _): Promise { return Promise.reject(obj); } // Note: We can't rename this method into `catch`, as this is not a valid // method name in Dart. @@ -29,8 +29,8 @@ export class PromiseWrapper { return Promise.all(promises); } - static then(promise: Promise, success: (value: any) => T | Thenable, - rejection?: (error: any, stack?: any) => T | Thenable): Promise { + static then(promise: Promise, success: (value: T) => U | Thenable, + rejection?: (error: any, stack?: any) => U | Thenable): Promise { return promise.then(success, rejection); } @@ -66,7 +66,9 @@ export class TimerWrapper { } export class ObservableWrapper { - static subscribe(emitter: Observable, onNext, onThrow = null, onReturn = null): Object { + static subscribe(emitter: Observable, onNext: (value: T) => void, + onThrow: (exception: any) => void = null, + onReturn: () => void = null): Object { return emitter.observer({next: onNext, throw: onThrow, return: onReturn}); } @@ -109,7 +111,7 @@ export class EventEmitter extends Observable { } } - observer(generator): Rx.IDisposable { + observer(generator: any): Rx.IDisposable { return this._subject.observeOn(this._immediateScheduler) .subscribe((value) => { setTimeout(() => generator.next(value)); }, (error) => generator.throw ? generator.throw(error) : null, @@ -118,9 +120,9 @@ export class EventEmitter extends Observable { toRx(): Rx.Observable { return this._subject; } - next(value) { this._subject.onNext(value); } + next(value: any) { this._subject.onNext(value); } - throw(error) { this._subject.onError(error); } + throw(error: any) { this._subject.onError(error); } - return (value?) { this._subject.onCompleted(); } + return (value?: any) { this._subject.onCompleted(); } } diff --git a/modules/angular2/src/facade/collection.ts b/modules/angular2/src/facade/collection.ts index d9c5128d00..ccedbd894b 100644 --- a/modules/angular2/src/facade/collection.ts +++ b/modules/angular2/src/facade/collection.ts @@ -55,7 +55,7 @@ var _clearValues: {(m: Map)} = (function() { export class MapWrapper { static clone(m: Map): Map { return createMapFromMap(m); } - static createFromStringMap(stringMap): Map { + static createFromStringMap(stringMap: StringMap): Map { var result = new Map(); for (var prop in stringMap) { result.set(prop, stringMap[prop]); @@ -146,13 +146,13 @@ export interface Predicate { (value: T, index?: number, array?: T[]): boolean export class ListWrapper { // JS has no way to express a staticly fixed size list, but dart does so we // keep both methods. - static createFixedSize(size): List { return new List(size); } - static createGrowableSize(size): List { return new List(size); } - static get(m, k): any { return m[k]; } - static set(m, k, v) { m[k] = v; } + static createFixedSize(size: number): List { return new List(size); } + static createGrowableSize(size: number): List { return new List(size); } + static get(m: List, k: number): T { return m[k]; } + static set(m: List, k: number, v: T) { m[k] = v; } static clone(array: List): T[] { return array.slice(0); } - static map(array, fn): any { return array.map(fn); } - static forEach(array: List, fn: Function) { + static map(array: List, fn: (T) => V): List { return array.map(fn); } + static forEach(array: List, fn: (T) => void) { for (var i = 0; i < array.length; i++) { fn(array[i]); } @@ -171,7 +171,7 @@ export class ListWrapper { } return null; } - static indexOf(array: List, value, startIndex = 0): number { + static indexOf(array: List, value: T, startIndex: number = 0): number { return array.indexOf(value, startIndex); } static reduce(list: List, @@ -186,26 +186,26 @@ export class ListWrapper { } return false; } - static contains(list: List, el): boolean { return list.indexOf(el) !== -1; } + static contains(list: List, el: T): boolean { return list.indexOf(el) !== -1; } static reversed(array: List): T[] { var a = ListWrapper.clone(array); return a.reverse(); } - static concat(a, b): List { return a.concat(b); } - static insert(list, index: int, value) { list.splice(index, 0, value); } - static removeAt(list: List, index: int): T { + static concat(a: List, b: List): List { return a.concat(b); } + static insert(list: List, index: number, value: T) { list.splice(index, 0, value); } + static removeAt(list: List, index: number): T { var res = list[index]; list.splice(index, 1); return res; } - static removeAll(list, items) { + static removeAll(list: List, items: List) { for (var i = 0; i < items.length; ++i) { var index = list.indexOf(items[i]); list.splice(index, 1); } } static removeLast(list: List): T { return list.pop(); } - static remove(list, el): boolean { + static remove(list: List, el: T): boolean { var index = list.indexOf(el); if (index > -1) { list.splice(index, 1); @@ -213,10 +213,10 @@ export class ListWrapper { } return false; } - static clear(list) { list.splice(0, list.length); } - static join(list, s: string): string { return list.join(s); } - static isEmpty(list): boolean { return list.length == 0; } - static fill(list: List, value, start: int = 0, end: int = null) { + static clear(list: List) { list.splice(0, list.length); } + static join(list: List, s: string): string { return list.join(s); } + static isEmpty(list: List): boolean { return list.length == 0; } + static fill(list: List, value: any, start: number = 0, end: number = null) { list.fill(value, start, end === null ? undefined : end); } static equals(a: List, b: List): boolean { @@ -226,10 +226,12 @@ export class ListWrapper { } return true; } - static slice(l: List, from: int = 0, to: int = null): List { + static slice(l: List, from: number = 0, to: number = null): List { return l.slice(from, to === null ? undefined : to); } - static splice(l: List, from: int, length: int): List { return l.splice(from, length); } + static splice(l: List, from: number, length: number): List { + return l.splice(from, length); + } static sort(l: List, compareFn?: (a: T, b: T) => number) { if (isPresent(compareFn)) { l.sort(compareFn); @@ -241,14 +243,14 @@ export class ListWrapper { static toJSON(l: List): string { return JSON.stringify(l); } } -export function isListLikeIterable(obj): boolean { +export function isListLikeIterable(obj: any): boolean { if (!isJsObject(obj)) return false; return isArray(obj) || (!(obj instanceof Map) && // JS Map are iterables but return entries as [k, v] Symbol.iterator in obj); // JS Iterable have a Symbol.iterator prop } -export function iterateListLike(obj, fn: Function) { +export function iterateListLike(obj: any, fn: Function) { if (isArray(obj)) { for (var i = 0; i < obj.length; i++) { fn(obj[i]); diff --git a/modules/angular2/src/facade/lang.ts b/modules/angular2/src/facade/lang.ts index 01b547ca8f..82b4c6f6e8 100644 --- a/modules/angular2/src/facade/lang.ts +++ b/modules/angular2/src/facade/lang.ts @@ -65,35 +65,35 @@ export function IMPLEMENTS(_):(target: T) => T { return (t) => t; } -export function isPresent(obj): boolean { +export function isPresent(obj: any): boolean { return obj !== undefined && obj !== null; } -export function isBlank(obj): boolean { +export function isBlank(obj: any): boolean { return obj === undefined || obj === null; } -export function isString(obj): boolean { +export function isString(obj: any): boolean { return typeof obj === "string"; } -export function isFunction(obj): boolean { +export function isFunction(obj: any): boolean { return typeof obj === "function"; } -export function isType(obj): boolean { +export function isType(obj: any): boolean { return isFunction(obj); } -export function isStringMap(obj): boolean { +export function isStringMap(obj: any): boolean { return typeof obj === 'object' && obj !== null; } -export function isPromise(obj): boolean { +export function isPromise(obj: any): boolean { return obj instanceof (_global).Promise; } -export function isArray(obj): boolean { +export function isArray(obj: any): boolean { return Array.isArray(obj); } @@ -126,7 +126,7 @@ export class StringWrapper { static charCodeAt(s: string, index: int): number { return s.charCodeAt(index); } - static split(s: string, regExp): List { return s.split(regExp); } + static split(s: string, regExp: RegExp): List { return s.split(regExp); } static equals(s: string, s2: string): boolean { return s === s2; } @@ -190,7 +190,7 @@ export class NumberParseError extends BaseException { export class NumberWrapper { static toFixed(n: number, fractionDigits: int): string { return n.toFixed(fractionDigits); } - static equal(a, b): boolean { return a === b; } + static equal(a: number, b: number): boolean { return a === b; } static parseIntAutoRadix(text: string): int { var result: int = parseInt(text); @@ -224,15 +224,15 @@ export class NumberWrapper { static get NaN(): number { return NaN; } - static isNaN(value): boolean { return isNaN(value); } + static isNaN(value: any): boolean { return isNaN(value); } - static isInteger(value): boolean { return Number.isInteger(value); } + static isInteger(value: any): boolean { return Number.isInteger(value); } } export var RegExp = _global.RegExp; export class RegExpWrapper { - static create(regExpStr, flags: string = ''): RegExp { + static create(regExpStr: string, flags: string = ''): RegExp { flags = flags.replace(/g/g, ''); return new _global.RegExp(regExpStr, flags + 'g'); } @@ -242,7 +242,7 @@ export class RegExpWrapper { return regExp.exec(input); } static test(regExp: RegExp, input: string): boolean { return regExp.test(input); } - static matcher(regExp, input): { + static matcher(regExp: RegExp, input: string): { re: RegExp; input: string } @@ -256,11 +256,16 @@ export class RegExpWrapper { } export class RegExpMatcherWrapper { - static next(matcher): string { return matcher.re.exec(matcher.input); } + static next(matcher: { + re: RegExp; + input: string + }): string[] { + return matcher.re.exec(matcher.input); + } } export class FunctionWrapper { - static apply(fn: Function, posArgs): any { return fn.apply(null, posArgs); } + static apply(fn: Function, posArgs: any): any { return fn.apply(null, posArgs); } } // JS has NaN !== NaN @@ -270,11 +275,11 @@ export function looseIdentical(a, b): boolean { // JS considers NaN is the same as NaN for map Key (while NaN !== NaN otherwise) // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map -export function getMapKey(value): any { +export function getMapKey(value: T): T { return value; } -export function normalizeBlank(obj): any { +export function normalizeBlank(obj: Object): any { return isBlank(obj) ? null : obj; } @@ -282,12 +287,12 @@ export function normalizeBool(obj: boolean): boolean { return isBlank(obj) ? false : obj; } -export function isJsObject(o): boolean { +export function isJsObject(o: any): boolean { return o !== null && (typeof o === "function" || typeof o === "object"); } -export function print(obj) { - if (obj instanceof Error) { +export function print(obj: Error | Object) { + if (obj instanceof BaseException) { console.log(obj.stack); } else { console.log(obj); @@ -297,7 +302,7 @@ export function print(obj) { // Can't be all uppercase as our transpiler would think it is a special directive... export class Json { static parse(s: string): Object { return _global.JSON.parse(s); } - static stringify(data): string { + static stringify(data: Object): string { // Dart doesn't take 3 arguments return _global.JSON.stringify(data, null, 2); } diff --git a/modules/angular2/src/forms/directives/checkbox_value_accessor.ts b/modules/angular2/src/forms/directives/checkbox_value_accessor.ts index 33c4596cb5..2ee2bb2ecc 100644 --- a/modules/angular2/src/forms/directives/checkbox_value_accessor.ts +++ b/modules/angular2/src/forms/directives/checkbox_value_accessor.ts @@ -37,7 +37,7 @@ export class CheckboxControlValueAccessor implements ControlValueAccessor { cd.valueAccessor = this; } - writeValue(value) { setProperty(this.renderer, this.elementRef, "checked", value); } + writeValue(value: any) { setProperty(this.renderer, this.elementRef, "checked", value); } get ngClassUntouched(): boolean { return isPresent(this.cd.control) ? this.cd.control.untouched : false; @@ -54,6 +54,6 @@ export class CheckboxControlValueAccessor implements ControlValueAccessor { return isPresent(this.cd.control) ? !this.cd.control.valid : false; } - registerOnChange(fn): void { this.onChange = fn; } - registerOnTouched(fn): void { this.onTouched = fn; } + registerOnChange(fn: (_) => {}): void { this.onChange = fn; } + registerOnTouched(fn: () => {}): void { this.onTouched = fn; } } diff --git a/modules/angular2/src/forms/directives/default_value_accessor.ts b/modules/angular2/src/forms/directives/default_value_accessor.ts index 66e4ec8dae..3a4a16ca0d 100644 --- a/modules/angular2/src/forms/directives/default_value_accessor.ts +++ b/modules/angular2/src/forms/directives/default_value_accessor.ts @@ -38,7 +38,7 @@ export class DefaultValueAccessor implements ControlValueAccessor { cd.valueAccessor = this; } - writeValue(value) { + writeValue(value: any) { // both this.value and setProperty are required at the moment // remove when a proper imperative API is provided var normalizedValue = isBlank(value) ? '' : value; @@ -60,7 +60,7 @@ export class DefaultValueAccessor implements ControlValueAccessor { return isPresent(this.cd.control) ? !this.cd.control.valid : false; } - registerOnChange(fn): void { this.onChange = fn; } + registerOnChange(fn: (_) => void): void { this.onChange = fn; } - registerOnTouched(fn): void { this.onTouched = fn; } + registerOnTouched(fn: () => void): void { this.onTouched = fn; } } diff --git a/modules/angular2/src/forms/directives/ng_form_control.ts b/modules/angular2/src/forms/directives/ng_form_control.ts index c67ac68eb9..36937f2938 100644 --- a/modules/angular2/src/forms/directives/ng_form_control.ts +++ b/modules/angular2/src/forms/directives/ng_form_control.ts @@ -79,7 +79,7 @@ export class NgFormControl extends NgControl { this.ngValidators = ngValidators; } - onChange(c) { + onChange(c: StringMap) { if (!this._added) { setUpControl(this.form, this); this.form.updateValidity(); diff --git a/modules/angular2/src/forms/directives/ng_model.ts b/modules/angular2/src/forms/directives/ng_model.ts index 7ee53645f3..f856949d70 100644 --- a/modules/angular2/src/forms/directives/ng_model.ts +++ b/modules/angular2/src/forms/directives/ng_model.ts @@ -49,7 +49,7 @@ export class NgModel extends NgControl { this.ngValidators = ngValidators; } - onChange(c) { + onChange(c: StringMap) { if (!this._added) { setUpControl(this._control, this); this._control.updateValidity(); diff --git a/modules/angular2/src/forms/directives/select_control_value_accessor.ts b/modules/angular2/src/forms/directives/select_control_value_accessor.ts index ca393bf40a..72b28bd0b8 100644 --- a/modules/angular2/src/forms/directives/select_control_value_accessor.ts +++ b/modules/angular2/src/forms/directives/select_control_value_accessor.ts @@ -49,7 +49,7 @@ export class SelectControlValueAccessor implements ControlValueAccessor { this._updateValueWhenListOfOptionsChanges(query); } - writeValue(value) { + writeValue(value: any) { this.value = value; setProperty(this.renderer, this.elementRef, "value", value); } @@ -69,8 +69,8 @@ export class SelectControlValueAccessor implements ControlValueAccessor { return isPresent(this.cd.control) ? !this.cd.control.valid : false; } - registerOnChange(fn): void { this.onChange = fn; } - registerOnTouched(fn): void { this.onTouched = fn; } + registerOnChange(fn: () => any): void { this.onChange = fn; } + registerOnTouched(fn: () => any): void { this.onTouched = fn; } private _updateValueWhenListOfOptionsChanges(query: QueryList) { query.onChange(() => this.writeValue(this.value)); diff --git a/modules/angular2/src/forms/model.ts b/modules/angular2/src/forms/model.ts index 9adf182574..7b8536fe15 100644 --- a/modules/angular2/src/forms/model.ts +++ b/modules/angular2/src/forms/model.ts @@ -22,7 +22,7 @@ function _find(c: AbstractControl, path: List| string) { if (!(path instanceof List)) { path = StringWrapper.split(path, new RegExp("/")); } - if (ListWrapper.isEmpty(path)) return null; + if (path instanceof List && ListWrapper.isEmpty(path)) return null; return ListWrapper.reduce(>path, (v, name) => { if (v instanceof ControlGroup) { @@ -85,7 +85,7 @@ export class AbstractControl { } } - setParent(parent) { this._parent = parent; } + setParent(parent: ControlGroup | ControlArray) { this._parent = parent; } updateValidity({onlySelf}: {onlySelf?: boolean} = {}): void { onlySelf = isPresent(onlySelf) ? onlySelf : false; diff --git a/modules/angular2/src/http/backends/mock_backend.ts b/modules/angular2/src/http/backends/mock_backend.ts index f74e021acb..b51383704f 100644 --- a/modules/angular2/src/http/backends/mock_backend.ts +++ b/modules/angular2/src/http/backends/mock_backend.ts @@ -90,7 +90,7 @@ export class MockConnection { * returned * from {@link Http}. */ - mockError(err?) { + mockError(err?: Error) { // Matches XHR semantics this.readyState = ReadyStates.DONE; ObservableWrapper.callThrow(this.response, err); @@ -185,8 +185,8 @@ export class MockBackend { constructor() { this.connectionsArray = []; this.connections = new EventEmitter(); - ObservableWrapper.subscribe(this.connections, - connection => this.connectionsArray.push(connection)); + ObservableWrapper.subscribe( + this.connections, connection => this.connectionsArray.push(connection)); this.pendingConnections = new EventEmitter(); } @@ -207,7 +207,9 @@ export class MockBackend { * * This method only exists in the mock implementation, not in real Backends. */ - resolveAllConnections() { ObservableWrapper.subscribe(this.connections, c => c.readyState = 4); } + resolveAllConnections() { + ObservableWrapper.subscribe(this.connections, c => c.readyState = 4); + } /** * Creates a new {@link MockConnection}. This is equivalent to calling `new diff --git a/modules/angular2/src/http/headers.ts b/modules/angular2/src/http/headers.ts index ccab309d00..d56192e794 100644 --- a/modules/angular2/src/http/headers.ts +++ b/modules/angular2/src/http/headers.ts @@ -31,7 +31,7 @@ export class Headers { if (headers instanceof Headers) { this._headersMap = (headers)._headersMap; } else if (headers instanceof StringMap) { - this._headersMap = MapWrapper.createFromStringMap(headers); + this._headersMap = MapWrapper.createFromStringMap>(headers); MapWrapper.forEach(this._headersMap, (v, k) => { if (!isListLikeIterable(v)) { var list = []; diff --git a/modules/angular2/src/http/url_search_params.ts b/modules/angular2/src/http/url_search_params.ts index 1481a5c958..596f54f076 100644 --- a/modules/angular2/src/http/url_search_params.ts +++ b/modules/angular2/src/http/url_search_params.ts @@ -61,5 +61,5 @@ export class URLSearchParams { return ListWrapper.join(paramsList, '&'); } - delete (param): void { MapWrapper.delete(this.paramsMap, param); } + delete (param: string): void { MapWrapper.delete(this.paramsMap, param); } } diff --git a/modules/angular2/src/mock/location_mock.ts b/modules/angular2/src/mock/location_mock.ts index 868c61f349..e8ecb12253 100644 --- a/modules/angular2/src/mock/location_mock.ts +++ b/modules/angular2/src/mock/location_mock.ts @@ -30,7 +30,7 @@ export class SpyLocation extends SpyObject { simulateUrlPop(pathname: string) { ObservableWrapper.callNext(this._subject, {'url': pathname}); } - normalizeAbsolutely(url): string { return this._baseHref + url; } + normalizeAbsolutely(url: string): string { return this._baseHref + url; } go(url: string) { url = this.normalizeAbsolutely(url); @@ -49,9 +49,10 @@ export class SpyLocation extends SpyObject { // TODO } - subscribe(onNext, onThrow = null, onReturn = null) { + subscribe(onNext: (value: any) => void, onThrow: (error: any) => void = null, + onReturn: () => void = null) { ObservableWrapper.subscribe(this._subject, onNext, onThrow, onReturn); } - noSuchMethod(m) { super.noSuchMethod(m); } + noSuchMethod(m: any) { super.noSuchMethod(m); } } diff --git a/modules/angular2/src/mock/mock_location_strategy.ts b/modules/angular2/src/mock/mock_location_strategy.ts index 689e0434ec..6921dc6f00 100644 --- a/modules/angular2/src/mock/mock_location_strategy.ts +++ b/modules/angular2/src/mock/mock_location_strategy.ts @@ -11,7 +11,7 @@ export class MockLocationStrategy extends LocationStrategy { _subject: EventEmitter = new EventEmitter(); constructor() { super(); } - simulatePopState(url): void { + simulatePopState(url: string): void { this.internalPath = url; ObservableWrapper.callNext(this._subject, null); } @@ -28,7 +28,7 @@ export class MockLocationStrategy extends LocationStrategy { this.urlChanges.push(url); } - onPopState(fn): void { ObservableWrapper.subscribe(this._subject, fn); } + onPopState(fn: (value: any) => void): void { ObservableWrapper.subscribe(this._subject, fn); } getBaseHref(): string { return this.internalBaseHref; } } diff --git a/modules/angular2/src/mock/ng_zone_mock.ts b/modules/angular2/src/mock/ng_zone_mock.ts index 64b53a39d1..3a82e2f5e6 100644 --- a/modules/angular2/src/mock/ng_zone_mock.ts +++ b/modules/angular2/src/mock/ng_zone_mock.ts @@ -3,7 +3,7 @@ import {NgZone} from 'angular2/src/core/zone/ng_zone'; export class MockNgZone extends NgZone { constructor() { super({enableLongStackTrace: false}); } - run(fn): any { return fn(); } + run(fn: Function): any { return fn(); } - runOutsideAngular(fn): any { return fn(); } + runOutsideAngular(fn: Function): any { return fn(); } } diff --git a/modules/angular2/src/reflection/reflection_capabilities.ts b/modules/angular2/src/reflection/reflection_capabilities.ts index 32fe69515a..6c1d439ad0 100644 --- a/modules/angular2/src/reflection/reflection_capabilities.ts +++ b/modules/angular2/src/reflection/reflection_capabilities.ts @@ -109,10 +109,10 @@ export class ReflectionCapabilities implements PlatformReflectionCapabilities { return result; } - parameters(typeOfFunc): List> { + parameters(typeOfFunc: Type): List> { // Prefer the direct API. - if (isPresent(typeOfFunc.parameters)) { - return typeOfFunc.parameters; + if (isPresent((typeOfFunc).parameters)) { + return (typeOfFunc).parameters; } if (isPresent(this._reflect) && isPresent(this._reflect.getMetadata)) { var paramAnnotations = this._reflect.getMetadata('parameters', typeOfFunc); @@ -121,13 +121,13 @@ export class ReflectionCapabilities implements PlatformReflectionCapabilities { return this._zipTypesAndAnnotaions(paramTypes, paramAnnotations); } } - return ListWrapper.createFixedSize(typeOfFunc.length); + return ListWrapper.createFixedSize((typeOfFunc).length); } - annotations(typeOfFunc): List { + annotations(typeOfFunc: Type): List { // Prefer the direct API. - if (isPresent(typeOfFunc.annotations)) { - var annotations = typeOfFunc.annotations; + if (isPresent((typeOfFunc).annotations)) { + var annotations = (typeOfFunc).annotations; if (isFunction(annotations) && annotations.annotations) { annotations = annotations.annotations; } @@ -140,7 +140,9 @@ export class ReflectionCapabilities implements PlatformReflectionCapabilities { return []; } - interfaces(type): List { throw new BaseException("JavaScript does not support interfaces"); } + interfaces(type: Type): List { + throw new BaseException("JavaScript does not support interfaces"); + } getter(name: string): GetterFn { return new Function('o', 'return o.' + name + ';'); } diff --git a/modules/angular2/src/reflection/reflector.ts b/modules/angular2/src/reflection/reflector.ts index c712787462..1ebd0ce72f 100644 --- a/modules/angular2/src/reflection/reflector.ts +++ b/modules/angular2/src/reflection/reflector.ts @@ -57,7 +57,7 @@ export class Reflector { } } - parameters(typeOrFunc): List { + parameters(typeOrFunc: /*Type*/ any): List { if (this._injectableInfo.has(typeOrFunc)) { return this._getTypeInfoField(typeOrFunc, "parameters", []); } else { @@ -65,7 +65,7 @@ export class Reflector { } } - annotations(typeOrFunc): List { + annotations(typeOrFunc: /*Type*/ any): List { if (this._injectableInfo.has(typeOrFunc)) { return this._getTypeInfoField(typeOrFunc, "annotations", []); } else { @@ -73,7 +73,7 @@ export class Reflector { } } - interfaces(type): List { + interfaces(type: Type): List { if (this._injectableInfo.has(type)) { return this._getTypeInfoField(type, "interfaces", []); } else { diff --git a/modules/angular2/src/render/dom/compiler/compile_control.ts b/modules/angular2/src/render/dom/compiler/compile_control.ts index ebb3e06b4e..05bec0a852 100644 --- a/modules/angular2/src/render/dom/compiler/compile_control.ts +++ b/modules/angular2/src/render/dom/compiler/compile_control.ts @@ -17,7 +17,7 @@ export class CompileControl { constructor(public _steps: List) {} // only public so that it can be used by compile_pipeline - internalProcess(results: any[], startStepIndex, parent: CompileElement, + internalProcess(results: any[], startStepIndex: number, parent: CompileElement, current: CompileElement): CompileElement[] { this._results = results; var previousStepIndex = this._currentStepIndex; diff --git a/modules/angular2/src/render/dom/compiler/compile_pipeline.ts b/modules/angular2/src/render/dom/compiler/compile_pipeline.ts index ec7d441dab..095e609864 100644 --- a/modules/angular2/src/render/dom/compiler/compile_pipeline.ts +++ b/modules/angular2/src/render/dom/compiler/compile_pipeline.ts @@ -17,7 +17,7 @@ export class CompilePipeline { this._control = new CompileControl(steps); } - process(rootElement, protoViewType: ViewType = null, + process(rootElement: HTMLElement, protoViewType: ViewType = null, compilationCtxtDescription: string = ''): List { if (isBlank(protoViewType)) { protoViewType = ViewType.COMPONENT; diff --git a/modules/angular2/src/render/dom/compiler/compiler.ts b/modules/angular2/src/render/dom/compiler/compiler.ts index 2ba228e29e..b2f04a3573 100644 --- a/modules/angular2/src/render/dom/compiler/compiler.ts +++ b/modules/angular2/src/render/dom/compiler/compiler.ts @@ -36,6 +36,7 @@ export class DomCompiler extends RenderCompiler { return PromiseWrapper.then( tplPromise, (el) => this._compileTemplate(view, el, ViewType.COMPONENT), (e) => { throw new BaseException(`Failed to load the template for "${view.componentId}" : ${e}`); + return null; }); } diff --git a/modules/angular2/src/render/dom/compiler/selector.ts b/modules/angular2/src/render/dom/compiler/selector.ts index 436eaee8b9..74e7357013 100644 --- a/modules/angular2/src/render/dom/compiler/selector.ts +++ b/modules/angular2/src/render/dom/compiler/selector.ts @@ -246,7 +246,7 @@ export class SelectorMatcher { * @param matchedCallback This callback will be called with the object handed into `addSelectable` * @return boolean true if a match was found */ - match(cssSelector: CssSelector, matchedCallback /*: (CssSelector, any) => void*/): boolean { + match(cssSelector: CssSelector, matchedCallback: (CssSelector, any) => void): boolean { var result = false; var element = cssSelector.element; var classNames = cssSelector.classNames; @@ -353,7 +353,7 @@ export class SelectorContext { this.notSelectors = selector.notSelectors; } - finalize(cssSelector: CssSelector, callback /*: (CssSelector, any) => void*/): boolean { + finalize(cssSelector: CssSelector, callback: (CssSelector, any) => void): boolean { var result = true; if (this.notSelectors.length > 0 && (isBlank(this.listContext) || !this.listContext.alreadyMatched)) { diff --git a/modules/angular2/src/render/dom/compiler/text_interpolation_parser.ts b/modules/angular2/src/render/dom/compiler/text_interpolation_parser.ts index 480c5aa4b6..dfa7f8da6d 100644 --- a/modules/angular2/src/render/dom/compiler/text_interpolation_parser.ts +++ b/modules/angular2/src/render/dom/compiler/text_interpolation_parser.ts @@ -22,14 +22,15 @@ export class TextInterpolationParser implements CompileStep { for (var i = 0; i < childNodes.length; i++) { var node = childNodes[i]; if (DOM.isTextNode(node)) { - var text = DOM.nodeValue(node); + var textNode = node; + var text = DOM.nodeValue(textNode); var expr = this._parser.parseInterpolation(text, current.elementDescription); if (isPresent(expr)) { - DOM.setText(node, ' '); + DOM.setText(textNode, ' '); if (current.element === current.inheritedProtoView.rootElement) { - current.inheritedProtoView.bindRootText(node, expr); + current.inheritedProtoView.bindRootText(textNode, expr); } else { - current.bindElement().bindText(node, expr); + current.bindElement().bindText(textNode, expr); } } } diff --git a/modules/angular2/src/render/dom/events/event_manager.ts b/modules/angular2/src/render/dom/events/event_manager.ts index 39b4b1f129..c67d52ce1e 100644 --- a/modules/angular2/src/render/dom/events/event_manager.ts +++ b/modules/angular2/src/render/dom/events/event_manager.ts @@ -12,7 +12,7 @@ export class EventManager { } } - addEventListener(element, eventName: string, handler: Function) { + addEventListener(element: HTMLElement, eventName: string, handler: Function) { var withoutBubbleSymbol = this._removeBubbleSymbol(eventName); var plugin = this._findPluginFor(withoutBubbleSymbol); plugin.addEventListener(element, withoutBubbleSymbol, handler, @@ -53,11 +53,12 @@ export class EventManagerPlugin { // addEventListener methods. supports(eventName: string): boolean { return false; } - addEventListener(element, eventName: string, handler: Function, shouldSupportBubble: boolean) { + addEventListener(element: HTMLElement, eventName: string, handler: Function, + shouldSupportBubble: boolean) { throw "not implemented"; } - addGlobalEventListener(element, eventName: string, handler: Function, + addGlobalEventListener(element: string, eventName: string, handler: Function, shouldSupportBubble: boolean): Function { throw "not implemented"; } @@ -70,7 +71,8 @@ export class DomEventsPlugin extends EventManagerPlugin { // events. supports(eventName: string): boolean { return true; } - addEventListener(element, eventName: string, handler: Function, shouldSupportBubble: boolean) { + addEventListener(element: HTMLElement, eventName: string, handler: Function, + shouldSupportBubble: boolean) { var outsideHandler = this._getOutsideHandler(shouldSupportBubble, element, handler, this.manager._zone); this.manager._zone.runOutsideAngular(() => { DOM.on(element, eventName, outsideHandler); }); @@ -85,12 +87,14 @@ export class DomEventsPlugin extends EventManagerPlugin { () => { return DOM.onAndCancel(element, eventName, outsideHandler); }); } - _getOutsideHandler(shouldSupportBubble: boolean, element, handler: Function, zone: NgZone) { + _getOutsideHandler(shouldSupportBubble: boolean, element: HTMLElement, handler: Function, + zone: NgZone) { return shouldSupportBubble ? DomEventsPlugin.bubbleCallback(element, handler, zone) : DomEventsPlugin.sameElementCallback(element, handler, zone); } - static sameElementCallback(element, handler, zone): (event: Event) => void { + static sameElementCallback(element: HTMLElement, handler: Function, zone: NgZone): + (event: Event) => void { return (event) => { if (event.target === element) { zone.run(() => handler(event)); @@ -98,7 +102,8 @@ export class DomEventsPlugin extends EventManagerPlugin { }; } - static bubbleCallback(element, handler, zone): (event: Event) => void { + static bubbleCallback(element: HTMLElement, handler: Function, zone: NgZone): + (event: Event) => void { return (event) => zone.run(() => handler(event)); } } diff --git a/modules/angular2/src/render/dom/events/hammer_gestures.ts b/modules/angular2/src/render/dom/events/hammer_gestures.ts index 39c870d858..3f14f531fe 100644 --- a/modules/angular2/src/render/dom/events/hammer_gestures.ts +++ b/modules/angular2/src/render/dom/events/hammer_gestures.ts @@ -16,7 +16,8 @@ export class HammerGesturesPlugin extends HammerGesturesPluginCommon { return true; } - addEventListener(element, eventName: string, handler: Function, shouldSupportBubble: boolean) { + addEventListener(element: HTMLElement, eventName: string, handler: Function, + shouldSupportBubble: boolean) { if (shouldSupportBubble) throw new BaseException('Hammer.js plugin does not support bubbling gestures.'); var zone = this.manager.getZone(); diff --git a/modules/angular2/src/render/dom/events/key_events.ts b/modules/angular2/src/render/dom/events/key_events.ts index c4134bee86..29bf157ff0 100644 --- a/modules/angular2/src/render/dom/events/key_events.ts +++ b/modules/angular2/src/render/dom/events/key_events.ts @@ -9,6 +9,7 @@ import { } from 'angular2/src/facade/lang'; import {StringMapWrapper, ListWrapper} from 'angular2/src/facade/collection'; import {EventManagerPlugin} from './event_manager'; +import {NgZone} from 'angular2/src/core/zone/ng_zone'; var modifierKeys = ['alt', 'control', 'meta', 'shift']; var modifierKeyGetters: StringMap = { @@ -25,7 +26,8 @@ export class KeyEventsPlugin extends EventManagerPlugin { return isPresent(KeyEventsPlugin.parseEventName(eventName)); } - addEventListener(element, eventName: string, handler: Function, shouldSupportBubble: boolean) { + addEventListener(element: HTMLElement, eventName: string, handler: (Event: any) => any, + shouldSupportBubble: boolean) { var parsedEvent = KeyEventsPlugin.parseEventName(eventName); var outsideHandler = KeyEventsPlugin.eventCallback(element, shouldSupportBubble, @@ -68,7 +70,7 @@ export class KeyEventsPlugin extends EventManagerPlugin { return result; } - static getEventFullKey(event): string { + static getEventFullKey(event: Event): string { var fullKey = ''; var key = DOM.getEventKey(event); key = key.toLowerCase(); @@ -89,8 +91,8 @@ export class KeyEventsPlugin extends EventManagerPlugin { return fullKey; } - static eventCallback(element, shouldSupportBubble, fullKey, handler, zone): - (event: Event) => void { + static eventCallback(element: HTMLElement, shouldSupportBubble: boolean, fullKey: any, + handler: (Event) => any, zone: NgZone): (event: Event) => void { return (event) => { var correctElement = shouldSupportBubble || event.target === element; if (correctElement && StringWrapper.equals(KeyEventsPlugin.getEventFullKey(event), fullKey)) { diff --git a/modules/angular2/src/render/dom/shadow_dom/emulated_scoped_shadow_dom_strategy.ts b/modules/angular2/src/render/dom/shadow_dom/emulated_scoped_shadow_dom_strategy.ts index 1fab2275a4..a2fa5c5bc7 100644 --- a/modules/angular2/src/render/dom/shadow_dom/emulated_scoped_shadow_dom_strategy.ts +++ b/modules/angular2/src/render/dom/shadow_dom/emulated_scoped_shadow_dom_strategy.ts @@ -26,7 +26,7 @@ import { export class EmulatedScopedShadowDomStrategy extends EmulatedUnscopedShadowDomStrategy { constructor(styleHost) { super(styleHost); } - processStyleElement(hostComponentId: string, templateUrl: string, styleEl): void { + processStyleElement(hostComponentId: string, templateUrl: string, styleEl: Element): void { let cssText = DOM.getText(styleEl); cssText = shimCssForComponent(cssText, hostComponentId); DOM.setText(styleEl, cssText); @@ -38,7 +38,7 @@ export class EmulatedScopedShadowDomStrategy extends EmulatedUnscopedShadowDomSt insertStyleElement(this.styleHost, styleEl); } - processElement(hostComponentId: string, elementComponentId: string, element): void { + processElement(hostComponentId: string, elementComponentId: string, element: Element): void { // Shim the element as a child of the compiled component if (isPresent(hostComponentId)) { var contentAttribute = getContentAttribute(getComponentId(hostComponentId)); diff --git a/modules/angular2/src/render/dom/shadow_dom/emulated_unscoped_shadow_dom_strategy.ts b/modules/angular2/src/render/dom/shadow_dom/emulated_unscoped_shadow_dom_strategy.ts index 0d5d62fd46..93b9980540 100644 --- a/modules/angular2/src/render/dom/shadow_dom/emulated_unscoped_shadow_dom_strategy.ts +++ b/modules/angular2/src/render/dom/shadow_dom/emulated_unscoped_shadow_dom_strategy.ts @@ -17,7 +17,7 @@ export class EmulatedUnscopedShadowDomStrategy extends ShadowDomStrategy { hasNativeContentElement(): boolean { return false; } - processStyleElement(hostComponentId: string, templateUrl: string, styleEl): void { + processStyleElement(hostComponentId: string, templateUrl: string, styleEl: Element): void { var cssText = DOM.getText(styleEl); insertSharedStyleText(cssText, this.styleHost, styleEl); } diff --git a/modules/angular2/src/render/dom/shadow_dom/shadow_css.ts b/modules/angular2/src/render/dom/shadow_dom/shadow_css.ts index 3a8587aed7..5b4adfa38f 100644 --- a/modules/angular2/src/render/dom/shadow_dom/shadow_css.ts +++ b/modules/angular2/src/render/dom/shadow_dom/shadow_css.ts @@ -145,7 +145,7 @@ export class ShadowCss { * Shim a style element with the given selector. Returns cssText that can * be included in the document via WebComponents.ShadowCSS.addCssToDocument(css). */ - shimStyle(style, selector: string, hostSelector: string = ''): string { + shimStyle(style: string, selector: string, hostSelector: string = ''): string { var cssText = DOM.getText(style); return this.shimCssText(cssText, selector, hostSelector); } diff --git a/modules/angular2/src/render/dom/shadow_dom/shadow_dom_strategy.ts b/modules/angular2/src/render/dom/shadow_dom/shadow_dom_strategy.ts index f69be75f8e..5de0746a6f 100644 --- a/modules/angular2/src/render/dom/shadow_dom/shadow_dom_strategy.ts +++ b/modules/angular2/src/render/dom/shadow_dom/shadow_dom_strategy.ts @@ -5,8 +5,9 @@ export class ShadowDomStrategy { hasNativeContentElement(): boolean { return true; } // An optional step that can modify the template style elements. - processStyleElement(hostComponentId: string, templateUrl: string, styleElement): void {} + processStyleElement(hostComponentId: string, templateUrl: string, styleElement: HTMLStyleElement): + void {} // An optional step that can modify the template elements (style elements exlcuded). - processElement(hostComponentId: string, elementComponentId: string, element): void {} + processElement(hostComponentId: string, elementComponentId: string, element: HTMLElement): void {} } diff --git a/modules/angular2/src/render/dom/view/proto_view_builder.ts b/modules/angular2/src/render/dom/view/proto_view_builder.ts index 65939eb92e..0720f34f82 100644 --- a/modules/angular2/src/render/dom/view/proto_view_builder.ts +++ b/modules/angular2/src/render/dom/view/proto_view_builder.ts @@ -33,7 +33,7 @@ export class ProtoViewBuilder { constructor(public rootElement, public type: api.ViewType, public useNativeShadowDom: boolean = false) {} - bindElement(element, description = null): ElementBinderBuilder { + bindElement(element: HTMLElement, description: string = null): ElementBinderBuilder { var builder = new ElementBinderBuilder(this.elements.length, element, description); this.elements.push(builder); DOM.addClass(element, NG_BINDING_CLASS); @@ -41,7 +41,7 @@ export class ProtoViewBuilder { return builder; } - bindVariable(name, value) { + bindVariable(name: string, value: string) { // Store the variable map from value to variable, reflecting how it will be used later by // DomView. When a local is set to the view, a lookup for the variable name will take place // keyed @@ -53,7 +53,9 @@ export class ProtoViewBuilder { // Note: We don't store the node index until the compilation is complete, // as the compiler might change the order of elements. - bindRootText(textNode, expression) { this.rootTextBindings.set(textNode, expression); } + bindRootText(textNode: Text, expression: ASTWithSource) { + this.rootTextBindings.set(textNode, expression); + } build(): api.ProtoViewDto { var domElementBinders = []; @@ -140,7 +142,7 @@ export class ElementBinderBuilder { constructor(public index: number, public element, description: string) {} - setParent(parent: ElementBinderBuilder, distanceToParent): ElementBinderBuilder { + setParent(parent: ElementBinderBuilder, distanceToParent: number): ElementBinderBuilder { this.parent = parent; if (isPresent(parent)) { this.distanceToParent = distanceToParent; @@ -160,7 +162,7 @@ export class ElementBinderBuilder { return directive; } - bindNestedProtoView(rootElement): ProtoViewBuilder { + bindNestedProtoView(rootElement: HTMLElement): ProtoViewBuilder { if (isPresent(this.nestedProtoView)) { throw new BaseException('Only one nested view per element is allowed'); } @@ -178,7 +180,7 @@ export class ElementBinderBuilder { this.propertyBindingsToDirectives.add(name); } - bindVariable(name, value) { + bindVariable(name: string, value: string) { // When current is a view root, the variable bindings are set to the *nested* proto view. // The root view conceptually signifies a new "block scope" (the nested view), to which // the variables are bound. @@ -196,13 +198,15 @@ export class ElementBinderBuilder { } } - bindEvent(name, expression, target = null) { + bindEvent(name: string, expression: ASTWithSource, target: string = null) { this.eventBindings.push(this.eventBuilder.add(name, expression, target)); } // Note: We don't store the node index until the compilation is complete, // as the compiler might change the order of elements. - bindText(textNode, expression) { this.textBindings.set(textNode, expression); } + bindText(textNode: Text, expression: ASTWithSource) { + this.textBindings.set(textNode, expression); + } setComponentId(componentId: string) { this.componentId = componentId; } } @@ -231,7 +235,7 @@ export class DirectiveBuilder { this.hostPropertyBindings.set(name, expression); } - bindEvent(name, expression, target = null) { + bindEvent(name: string, expression: ASTWithSource, target: string = null) { this.eventBindings.push(this.eventBuilder.add(name, expression, target)); } } diff --git a/modules/angular2/src/render/dom/view/view.ts b/modules/angular2/src/render/dom/view/view.ts index c2c704a8fb..501fd74b72 100644 --- a/modules/angular2/src/render/dom/view/view.ts +++ b/modules/angular2/src/render/dom/view/view.ts @@ -67,7 +67,7 @@ export class DomView { setText(textIndex: number, value: string) { DOM.setText(this.boundTextNodes[textIndex], value); } - dispatchEvent(elementIndex, eventName, event): boolean { + dispatchEvent(elementIndex: number, eventName: string, event: Event): boolean { var allowDefaultBehavior = true; if (isPresent(this.eventDispatcher)) { var evalLocals = new Map(); diff --git a/modules/angular2/src/router/location.ts b/modules/angular2/src/router/location.ts index 2f78f7198e..8447b14a57 100644 --- a/modules/angular2/src/router/location.ts +++ b/modules/angular2/src/router/location.ts @@ -72,7 +72,8 @@ export class Location { back(): void { this._platformStrategy.back(); } - subscribe(onNext, onThrow = null, onReturn = null): void { + subscribe(onNext: (value: any) => void, onThrow: (exception: any) => void = null, + onReturn: () => void = null): void { ObservableWrapper.subscribe(this._subject, onNext, onThrow, onReturn); } } diff --git a/modules/angular2/src/router/location_strategy.ts b/modules/angular2/src/router/location_strategy.ts index 2b4a686677..f89c7ef5be 100644 --- a/modules/angular2/src/router/location_strategy.ts +++ b/modules/angular2/src/router/location_strategy.ts @@ -9,6 +9,6 @@ export class LocationStrategy { pushState(ctx: any, title: string, url: string): void { throw _abstract(); } forward(): void { throw _abstract(); } back(): void { throw _abstract(); } - onPopState(fn): void { throw _abstract(); } + onPopState(fn: (_) => any): void { throw _abstract(); } getBaseHref(): string { throw _abstract(); } } diff --git a/modules/angular2/src/router/route_registry.ts b/modules/angular2/src/router/route_registry.ts index bba7ec8726..068c68d8bf 100644 --- a/modules/angular2/src/router/route_registry.ts +++ b/modules/angular2/src/router/route_registry.ts @@ -37,7 +37,7 @@ export class RouteRegistry { /** * Given a component and a configuration object, add the route to this registry */ - config(parentComponent, config: RouteDefinition): void { + config(parentComponent: any, config: RouteDefinition): void { config = normalizeRouteConfig(config); var recognizer: RouteRecognizer = this._rules.get(parentComponent); @@ -61,7 +61,7 @@ export class RouteRegistry { /** * Reads the annotations of a component and configures the registry based on them */ - configFromComponent(component): void { + configFromComponent(component: any): void { if (!isType(component)) { return; } @@ -88,7 +88,7 @@ export class RouteRegistry { * Given a URL and a parent component, return the most specific instruction for navigating * the application into the state specified by the url */ - recognize(url: string, parentComponent): Promise { + recognize(url: string, parentComponent: any): Promise { var componentRecognizer = this._rules.get(parentComponent); if (isBlank(componentRecognizer)) { return PromiseWrapper.resolve(null); @@ -142,7 +142,7 @@ export class RouteRegistry { * Given a normalized list with component names and params like: `['user', {id: 3 }]` * generates a url with a leading slash relative to the provided `parentComponent`. */ - generate(linkParams: List, parentComponent): string { + generate(linkParams: List, parentComponent: any): string { let url = ''; let componentCursor = parentComponent; for (let i = 0; i < linkParams.length; i += 1) { diff --git a/modules/angular2/src/router/router.ts b/modules/angular2/src/router/router.ts index 08c30268b0..3107a43e94 100644 --- a/modules/angular2/src/router/router.ts +++ b/modules/angular2/src/router/router.ts @@ -196,7 +196,9 @@ export class Router { /** * Subscribe to URL updates from the router */ - subscribe(onNext): void { ObservableWrapper.subscribe(this._subject, onNext); } + subscribe(onNext: (value: any) => void): void { + ObservableWrapper.subscribe(this._subject, onNext); + } /** @@ -292,7 +294,7 @@ export class RootRouter extends Router { this.navigate(location.path()); } - commit(instruction): Promise { + commit(instruction: Instruction): Promise { return super.commit(instruction) .then((_) => { this._location.go(instruction.accumulatedUrl); }); } diff --git a/modules/angular2/src/test_lib/utils.ts b/modules/angular2/src/test_lib/utils.ts index fc198a3655..1784d56d51 100644 --- a/modules/angular2/src/test_lib/utils.ts +++ b/modules/angular2/src/test_lib/utils.ts @@ -20,8 +20,8 @@ export function dispatchEvent(element, eventType) { DOM.dispatchEvent(element, DOM.createEvent(eventType)); } -export function el(html: string) { - return DOM.firstChild(DOM.content(DOM.createTemplate(html))); +export function el(html: string): HTMLElement { + return DOM.firstChild(DOM.content(DOM.createTemplate(html))); } var _RE_SPECIAL_CHARS = diff --git a/modules/angular2/src/web-workers/shared/serializer.ts b/modules/angular2/src/web-workers/shared/serializer.ts index 85f6e17d2f..f7c6c4ae77 100644 --- a/modules/angular2/src/web-workers/shared/serializer.ts +++ b/modules/angular2/src/web-workers/shared/serializer.ts @@ -42,7 +42,7 @@ export class Serializer { } // TODO: template this to return the type that is passed if possible - static deserialize(map, type: Type, data?): any { + static deserialize(map: List, type: Type, data?: any): any { if (!isPresent(map)) { return null; } @@ -69,7 +69,7 @@ export class Serializer { } } - static mapToObject(map, type?: Type): Object { + static mapToObject(map: Map, type?: Type): Object { var object = {}; var serialize = isPresent(type); @@ -88,7 +88,7 @@ export class Serializer { * If the values need to be deserialized pass in their type * and they will be deserialized before being placed in the map */ - static objectToMap(obj, type?: Type, data?): Map { + static objectToMap(obj: Object, type?: Type, data?: any): Map { if (isPresent(type)) { var map: Map = new Map(); StringMapWrapper.forEach( @@ -142,7 +142,7 @@ class ViewDefinitionSerializer { 'styles': view.styles }; } - static deserialize(obj): ViewDefinition { + static deserialize(obj: any): ViewDefinition { return new ViewDefinition({ componentId: obj.componentId, templateAbsUrl: obj.templateAbsUrl, template: obj.template, @@ -164,7 +164,7 @@ class DirectiveBinderSerializer { }; } - static deserialize(obj): DirectiveBinder { + static deserialize(obj: any): DirectiveBinder { return new DirectiveBinder({ directiveIndex: obj.directiveIndex, propertyBindings: Serializer.objectToMap(obj.propertyBindings, ASTWithSource, "binding"), @@ -189,7 +189,7 @@ class ElementBinderSerializer { }; } - static deserialize(obj): ElementBinder { + static deserialize(obj: any): ElementBinder { return new ElementBinder({ index: obj.index, parentIndex: obj.parentIndex, @@ -216,7 +216,7 @@ class ProtoViewDtoSerializer { }; } - static deserialize(obj): ProtoViewDto { + static deserialize(obj: any): ProtoViewDto { return new ProtoViewDto({ render: null, // TODO: fix render refs and write a serializer for them elementBinders: Serializer.deserialize(obj.elementBinders, ElementBinder), @@ -250,7 +250,7 @@ class DirectiveMetadataSerializer { }; return obj; } - static deserialize(obj): DirectiveMetadata { + static deserialize(obj: any): DirectiveMetadata { return new DirectiveMetadata({ id: obj.id, selector: obj.selector, diff --git a/modules/angular2/test/change_detection/pipes/iterable_changes_spec.ts b/modules/angular2/test/change_detection/pipes/iterable_changes_spec.ts index 2691b36796..a1cc9d57ff 100644 --- a/modules/angular2/test/change_detection/pipes/iterable_changes_spec.ts +++ b/modules/angular2/test/change_detection/pipes/iterable_changes_spec.ts @@ -207,7 +207,7 @@ export function main() { let l = [NumberWrapper.NaN, NumberWrapper.NaN]; changes.check(l); - ListWrapper.insert(l, 0, 'foo'); + ListWrapper.insert(l, 0, 'foo'); changes.check(l); expect(changes.toString()) .toEqual(iterableChangesAsString({ diff --git a/modules/angular2/test/core/compiler/proto_view_factory_spec.ts b/modules/angular2/test/core/compiler/proto_view_factory_spec.ts index 6d2cdef5e6..9b5719b372 100644 --- a/modules/angular2/test/core/compiler/proto_view_factory_spec.ts +++ b/modules/angular2/test/core/compiler/proto_view_factory_spec.ts @@ -76,8 +76,10 @@ export function main() { describe("createDirectiveVariableBindings", () => { it("should calculate directive variable bindings", () => { var dvbs = createDirectiveVariableBindings( - new renderApi.ElementBinder( - {variableBindings: MapWrapper.createFromStringMap({"exportName": "templateName"})}), + new renderApi.ElementBinder({ + variableBindings: + MapWrapper.createFromStringMap({"exportName": "templateName"}) + }), [ directiveBinding( {metadata: renderApi.DirectiveMetadata.create({exportAs: 'exportName'})}), @@ -85,13 +87,15 @@ export function main() { {metadata: renderApi.DirectiveMetadata.create({exportAs: 'otherName'})}) ]); - expect(dvbs).toEqual(MapWrapper.createFromStringMap({"templateName": 0})); + expect(dvbs).toEqual(MapWrapper.createFromStringMap({"templateName": 0})); }); it("should set exportAs to $implicit for component with exportAs = null", () => { var dvbs = createDirectiveVariableBindings( - new renderApi.ElementBinder( - {variableBindings: MapWrapper.createFromStringMap({"$implicit": "templateName"})}), + new renderApi.ElementBinder({ + variableBindings: + MapWrapper.createFromStringMap({"$implicit": "templateName"}) + }), [ directiveBinding({ metadata: renderApi.DirectiveMetadata.create( @@ -99,7 +103,7 @@ export function main() { }) ]); - expect(dvbs).toEqual(MapWrapper.createFromStringMap({"templateName": 0})); + expect(dvbs).toEqual(MapWrapper.createFromStringMap({"templateName": 0})); }); it("should throw we no directive exported with this name", () => { @@ -107,7 +111,7 @@ export function main() { createDirectiveVariableBindings( new renderApi.ElementBinder({ variableBindings: - MapWrapper.createFromStringMap({"someInvalidName": "templateName"}) + MapWrapper.createFromStringMap({"someInvalidName": "templateName"}) }), [ directiveBinding( @@ -120,7 +124,8 @@ export function main() { expect(() => { createDirectiveVariableBindings( new renderApi.ElementBinder({ - variableBindings: MapWrapper.createFromStringMap({"exportName": "templateName"}) + variableBindings: + MapWrapper.createFromStringMap({"exportName": "templateName"}) }), [ directiveBinding( @@ -148,11 +153,11 @@ export function main() { it('should merge the names in the template for all ElementBinders', () => { expect(createVariableLocations([ new renderApi.ElementBinder( - {variableBindings: MapWrapper.createFromStringMap({"x": "a"})}), + {variableBindings: MapWrapper.createFromStringMap({"x": "a"})}), new renderApi.ElementBinder( - {variableBindings: MapWrapper.createFromStringMap({"y": "b"})}) + {variableBindings: MapWrapper.createFromStringMap({"y": "b"})}) - ])).toEqual(MapWrapper.createFromStringMap({'a': 0, 'b': 1})); + ])).toEqual(MapWrapper.createFromStringMap({'a': 0, 'b': 1})); }); }); }); diff --git a/modules/angular2/test/di/injector_spec.ts b/modules/angular2/test/di/injector_spec.ts index 0b47c33b5d..84ba755a6d 100644 --- a/modules/angular2/test/di/injector_spec.ts +++ b/modules/angular2/test/di/injector_spec.ts @@ -206,7 +206,7 @@ export function main() { var injector = createInjector([ bind('originalEngine') .toClass(forwardRef(() => Engine)), - bind('aliasedEngine').toAlias(forwardRef(() => 'originalEngine')) + bind('aliasedEngine').toAlias(forwardRef(() => 'originalEngine')) ]); expect(injector.get('aliasedEngine')).toBeAnInstanceOf(Engine); }); diff --git a/modules/angular2/test/http/backends/jsonp_backend_spec.ts b/modules/angular2/test/http/backends/jsonp_backend_spec.ts index 87eb0fa2d9..7ec6a0e62f 100644 --- a/modules/angular2/test/http/backends/jsonp_backend_spec.ts +++ b/modules/angular2/test/http/backends/jsonp_backend_spec.ts @@ -18,6 +18,7 @@ import {bind, Injector} from 'angular2/di'; import {isPresent, StringWrapper} from 'angular2/src/facade/lang'; import {TimerWrapper} from 'angular2/src/facade/async'; import {Request} from 'angular2/src/http/static_request'; +import {Response} from 'angular2/src/http/static_response'; import {Map} from 'angular2/src/facade/collection'; import {RequestOptions, BaseRequestOptions} from 'angular2/src/http/base_request_options'; import {BaseResponseOptions, ResponseOptions} from 'angular2/src/http/base_response_options'; @@ -25,6 +26,7 @@ import {ResponseTypes, ReadyStates, RequestMethods} from 'angular2/src/http/enum var addEventListenerSpy; var existingScripts = []; +var unused: Response; class MockBrowserJsonp extends BrowserJsonp { src: string; @@ -87,7 +89,7 @@ export function main() { inject([AsyncTestCompleter], async => { let connection = new JSONPConnection(sampleRequest, new MockBrowserJsonp(), new ResponseOptions({type: ResponseTypes.Error})); - ObservableWrapper.subscribe(connection.response, res => { + ObservableWrapper.subscribe(connection.response, res => { expect(res.type).toBe(ResponseTypes.Error); async.done(); }); @@ -164,7 +166,7 @@ export function main() { it('should respond with data passed to callback', inject([AsyncTestCompleter], async => { let connection = new JSONPConnection(sampleRequest, new MockBrowserJsonp()); - ObservableWrapper.subscribe(connection.response, res => { + ObservableWrapper.subscribe(connection.response, res => { expect(res.json()).toEqual(({fake_payload: true, blob_id: 12345})); async.done(); }); diff --git a/modules/angular2/test/http/backends/xhr_backend_spec.ts b/modules/angular2/test/http/backends/xhr_backend_spec.ts index f6982c7d44..0a109dae2f 100644 --- a/modules/angular2/test/http/backends/xhr_backend_spec.ts +++ b/modules/angular2/test/http/backends/xhr_backend_spec.ts @@ -16,6 +16,7 @@ import {BrowserXhr} from 'angular2/src/http/backends/browser_xhr'; import {XHRConnection, XHRBackend} from 'angular2/src/http/backends/xhr_backend'; import {bind, Injector} from 'angular2/di'; import {Request} from 'angular2/src/http/static_request'; +import {Response} from 'angular2/src/http/static_response'; import {Headers} from 'angular2/src/http/headers'; import {Map} from 'angular2/src/facade/collection'; import {RequestOptions, BaseRequestOptions} from 'angular2/src/http/base_request_options'; @@ -28,6 +29,7 @@ var openSpy; var setRequestHeaderSpy; var addEventListenerSpy; var existingXHRs = []; +var unused: Response; class MockBrowserXHR extends BrowserXhr { abort: any; @@ -86,7 +88,7 @@ export function main() { inject([AsyncTestCompleter], async => { var connection = new XHRConnection(sampleRequest, new MockBrowserXHR(), new ResponseOptions({type: ResponseTypes.Error})); - ObservableWrapper.subscribe(connection.response, res => { + ObservableWrapper.subscribe(connection.response, res => { expect(res.type).toBe(ResponseTypes.Error); async.done(); }); diff --git a/modules/angular2/test/http/http_spec.ts b/modules/angular2/test/http/http_spec.ts index ccadc4e417..1d2d7fbd35 100644 --- a/modules/angular2/test/http/http_spec.ts +++ b/modules/angular2/test/http/http_spec.ts @@ -13,7 +13,7 @@ import { } from 'angular2/test_lib'; import {Http} from 'angular2/src/http/http'; import {Injector, bind} from 'angular2/di'; -import {MockBackend} from 'angular2/src/http/backends/mock_backend'; +import {MockBackend, MockConnection} from 'angular2/src/http/backends/mock_backend'; import {Response} from 'angular2/src/http/static_response'; import {RequestMethods} from 'angular2/src/http/enums'; import {BaseRequestOptions, RequestOptions} from 'angular2/src/http/base_request_options'; @@ -66,7 +66,7 @@ export function main() { it('should accept a fully-qualified request as its only parameter', inject([AsyncTestCompleter], (async) => { - ObservableWrapper.subscribe(backend.connections, c => { + ObservableWrapper.subscribe(backend.connections, c => { expect(c.request.url).toBe('https://google.com'); c.mockRespond(new Response(new ResponseOptions({body: 'Thank you'}))); async.done(); @@ -79,8 +79,9 @@ export function main() { it('should perform a get request for given url if only passed a string', inject([AsyncTestCompleter], (async) => { - ObservableWrapper.subscribe(backend.connections, c => c.mockRespond(baseResponse)); - ObservableWrapper.subscribe(http.request('http://basic.connection'), res => { + ObservableWrapper.subscribe(backend.connections, + c => c.mockRespond(baseResponse)); + ObservableWrapper.subscribe(http.request('http://basic.connection'), res => { expect(res.text()).toBe('base response'); async.done(); }); @@ -102,7 +103,7 @@ export function main() { describe('.get()', () => { it('should perform a get request for given url', inject([AsyncTestCompleter], async => { - ObservableWrapper.subscribe(backend.connections, c => { + ObservableWrapper.subscribe(backend.connections, c => { expect(c.request.method).toBe(RequestMethods.GET); backend.resolveAllConnections(); async.done(); @@ -114,7 +115,7 @@ export function main() { describe('.post()', () => { it('should perform a post request for given url', inject([AsyncTestCompleter], async => { - ObservableWrapper.subscribe(backend.connections, c => { + ObservableWrapper.subscribe(backend.connections, c => { expect(c.request.method).toBe(RequestMethods.POST); backend.resolveAllConnections(); async.done(); @@ -125,7 +126,7 @@ export function main() { it('should attach the provided body to the request', inject([AsyncTestCompleter], async => { var body = 'this is my post body'; - ObservableWrapper.subscribe(backend.connections, c => { + ObservableWrapper.subscribe(backend.connections, c => { expect(c.request.text()).toBe(body); backend.resolveAllConnections(); async.done(); @@ -137,7 +138,7 @@ export function main() { describe('.put()', () => { it('should perform a put request for given url', inject([AsyncTestCompleter], async => { - ObservableWrapper.subscribe(backend.connections, c => { + ObservableWrapper.subscribe(backend.connections, c => { expect(c.request.method).toBe(RequestMethods.PUT); backend.resolveAllConnections(); async.done(); @@ -147,7 +148,7 @@ export function main() { it('should attach the provided body to the request', inject([AsyncTestCompleter], async => { var body = 'this is my put body'; - ObservableWrapper.subscribe(backend.connections, c => { + ObservableWrapper.subscribe(backend.connections, c => { expect(c.request.text()).toBe(body); backend.resolveAllConnections(); async.done(); @@ -159,7 +160,7 @@ export function main() { describe('.delete()', () => { it('should perform a delete request for given url', inject([AsyncTestCompleter], async => { - ObservableWrapper.subscribe(backend.connections, c => { + ObservableWrapper.subscribe(backend.connections, c => { expect(c.request.method).toBe(RequestMethods.DELETE); backend.resolveAllConnections(); async.done(); @@ -171,7 +172,7 @@ export function main() { describe('.patch()', () => { it('should perform a patch request for given url', inject([AsyncTestCompleter], async => { - ObservableWrapper.subscribe(backend.connections, c => { + ObservableWrapper.subscribe(backend.connections, c => { expect(c.request.method).toBe(RequestMethods.PATCH); backend.resolveAllConnections(); async.done(); @@ -181,7 +182,7 @@ export function main() { it('should attach the provided body to the request', inject([AsyncTestCompleter], async => { var body = 'this is my patch body'; - ObservableWrapper.subscribe(backend.connections, c => { + ObservableWrapper.subscribe(backend.connections, c => { expect(c.request.text()).toBe(body); backend.resolveAllConnections(); async.done(); @@ -193,7 +194,7 @@ export function main() { describe('.head()', () => { it('should perform a head request for given url', inject([AsyncTestCompleter], async => { - ObservableWrapper.subscribe(backend.connections, c => { + ObservableWrapper.subscribe(backend.connections, c => { expect(c.request.method).toBe(RequestMethods.HEAD); backend.resolveAllConnections(); async.done(); diff --git a/modules/angular2/test/render/dom/compiler/directive_parser_spec.ts b/modules/angular2/test/render/dom/compiler/directive_parser_spec.ts index b390481d8d..53dd2230b4 100644 --- a/modules/angular2/test/render/dom/compiler/directive_parser_spec.ts +++ b/modules/angular2/test/render/dom/compiler/directive_parser_spec.ts @@ -232,25 +232,27 @@ var someDirectiveWithProps = DirectiveMetadata.create({ var someDirectiveWithHostProperties = DirectiveMetadata.create({ selector: '[some-decor-with-host-props]', - host: MapWrapper.createFromStringMap({'[hostProp]': 'dirProp'}) + host: MapWrapper.createFromStringMap({'[hostProp]': 'dirProp'}) }); var someDirectiveWithInvalidHostProperties = DirectiveMetadata.create({ selector: '[some-decor-with-invalid-host-props]', - host: MapWrapper.createFromStringMap({'[hostProp]': 'dirProp + dirProp2'}) + host: MapWrapper.createFromStringMap({'[hostProp]': 'dirProp + dirProp2'}) }); var someDirectiveWithHostAttributes = DirectiveMetadata.create({ selector: '[some-decor-with-host-attrs]', - host: MapWrapper.createFromStringMap({'attr_name': 'attr_val', 'class': 'foo bar'}) + host: MapWrapper.createFromStringMap({'attr_name': 'attr_val', 'class': 'foo bar'}) }); -var someDirectiveWithEvents = DirectiveMetadata.create( - {selector: '[some-decor-events]', host: MapWrapper.createFromStringMap({'(click)': 'doIt()'})}); +var someDirectiveWithEvents = DirectiveMetadata.create({ + selector: '[some-decor-events]', + host: MapWrapper.createFromStringMap({'(click)': 'doIt()'}) +}); var someDirectiveWithGlobalEvents = DirectiveMetadata.create({ selector: '[some-decor-globalevents]', - host: MapWrapper.createFromStringMap({'(window:resize)': 'doItGlobal()'}) + host: MapWrapper.createFromStringMap({'(window:resize)': 'doItGlobal()'}) }); var componentWithNonElementSelector = DirectiveMetadata.create({ diff --git a/modules/angular2/test/router/outlet_spec.ts b/modules/angular2/test/router/outlet_spec.ts index b5f66e6966..2993b5c7b8 100644 --- a/modules/angular2/test/router/outlet_spec.ts +++ b/modules/angular2/test/router/outlet_spec.ts @@ -257,7 +257,7 @@ export function main() { compile() .then((_) => rtr.config([new Route({path: '/...', component: LifecycleCmp})])) .then((_) => { - ObservableWrapper.subscribe(eventBus, (ev) => { + ObservableWrapper.subscribe(eventBus, (ev) => { if (ev.startsWith('parent activate')) { completer.resolve(true); } @@ -292,7 +292,7 @@ export function main() { .then((_) => rtr.config([new Route({path: '/...', component: LifecycleCmp})])) .then((_) => rtr.navigate('/parent-deactivate/child-deactivate')) .then((_) => { - ObservableWrapper.subscribe(eventBus, (ev) => { + ObservableWrapper.subscribe(eventBus, (ev) => { if (ev.startsWith('deactivate')) { completer.resolve(true); rootTC.detectChanges(); @@ -356,7 +356,7 @@ export function main() { compile() .then((_) => rtr.config([new Route({path: '/...', component: LifecycleCmp})])) .then((_) => { - ObservableWrapper.subscribe(eventBus, (ev) => { + ObservableWrapper.subscribe(eventBus, (ev) => { if (ev.startsWith('canActivate')) { completer.resolve(true); } @@ -376,7 +376,7 @@ export function main() { compile() .then((_) => rtr.config([new Route({path: '/...', component: LifecycleCmp})])) .then((_) => { - ObservableWrapper.subscribe(eventBus, (ev) => { + ObservableWrapper.subscribe(eventBus, (ev) => { if (ev.startsWith('canActivate')) { completer.resolve(false); } @@ -401,7 +401,7 @@ export function main() { expect(rootTC.nativeElement).toHaveText('canDeactivate {A}'); expect(log).toEqual(''); - ObservableWrapper.subscribe(eventBus, (ev) => { + ObservableWrapper.subscribe(eventBus, (ev) => { if (ev.startsWith('canDeactivate')) { completer.resolve(true); } @@ -426,7 +426,7 @@ export function main() { expect(rootTC.nativeElement).toHaveText('canDeactivate {A}'); expect(log).toEqual(''); - ObservableWrapper.subscribe(eventBus, (ev) => { + ObservableWrapper.subscribe(eventBus, (ev) => { if (ev.startsWith('canDeactivate')) { completer.resolve(false); } @@ -473,7 +473,7 @@ export function main() { expect(log).toEqual('canActivate: null -> /reuse-hooks/1;' + 'onActivate: null -> /reuse-hooks/1;'); - ObservableWrapper.subscribe(eventBus, (ev) => { + ObservableWrapper.subscribe(eventBus, (ev) => { if (ev.startsWith('canReuse')) { completer.resolve(true); } @@ -497,7 +497,7 @@ export function main() { expect(log).toEqual('canActivate: null -> /reuse-hooks/1;' + 'onActivate: null -> /reuse-hooks/1;'); - ObservableWrapper.subscribe(eventBus, (ev) => { + ObservableWrapper.subscribe(eventBus, (ev) => { if (ev.startsWith('canReuse')) { completer.resolve(false); } diff --git a/modules/benchpress/test/runner_spec.ts b/modules/benchpress/test/runner_spec.ts index db0e3814f4..4756ce8b68 100644 --- a/modules/benchpress/test/runner_spec.ts +++ b/modules/benchpress/test/runner_spec.ts @@ -153,5 +153,5 @@ class MockMetric extends Metric { class MockSampler extends Sampler { constructor() { super(); } - sample(): Promise { return PromiseWrapper.resolve(23); } + sample(): Promise { return PromiseWrapper.resolve(new SampleState([], [])); } } diff --git a/tools/tslint/requireParameterTypeRule.ts b/tools/tslint/requireParameterTypeRule.ts new file mode 100644 index 0000000000..2f6e944f22 --- /dev/null +++ b/tools/tslint/requireParameterTypeRule.ts @@ -0,0 +1,38 @@ +/// +/// + +export class Rule extends Lint.Rules.AbstractRule { + public static FAILURE_STRING = "missing type declaration"; + + public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { + const typedefWalker = new TypedefWalker(sourceFile, this.getOptions()); + return this.applyWithWalker(typedefWalker); + } +} + +class TypedefWalker extends Lint.RuleWalker { + public visitMethodDeclaration(node: ts.MethodDeclaration) { + if (node.name.getText().charAt(0) !== '_') { + node.parameters.forEach((p: ts.ParameterDeclaration) => { + // a parameter's "type" could be a specific string value, for example `fn(option: + // "someOption", anotherOption: number)` + if (p.type == null || p.type.kind !== ts.SyntaxKind.StringLiteral) { + this.checkTypeAnnotation(p.getEnd(), p.type, p.name); + } + }); + } + super.visitMethodDeclaration(node); + } + + private checkTypeAnnotation(location: number, typeAnnotation: ts.TypeNode, name?: ts.Node) { + if (typeAnnotation == null) { + let ns = ""; + if (name != null && name.kind === ts.SyntaxKind.Identifier) { + ns = (name).text; + } + if (ns.charAt(0) === '_') return; + let failure = this.createFailure(location, 1, "expected parameter " + ns + " to have a type"); + this.addFailure(failure); + } + } +} diff --git a/tools/tslint/requireReturnTypeRule.ts b/tools/tslint/requireReturnTypeRule.ts index 1c3b33fbf3..f1e3de778d 100644 --- a/tools/tslint/requireReturnTypeRule.ts +++ b/tools/tslint/requireReturnTypeRule.ts @@ -40,21 +40,20 @@ class TypedefWalker extends Lint.RuleWalker { } private handleCallSignature(node: ts.SignatureDeclaration) { - const location = (node.parameters != null) ? node.parameters.end : null; // set accessors can't have a return type. if (node.kind !== ts.SyntaxKind.SetAccessor) { - this.checkTypeAnnotation(location, node.type, node.name); + this.checkTypeAnnotation(node.type, node.name); } } - private checkTypeAnnotation(location: number, typeAnnotation: ts.TypeNode, name?: ts.Node) { + private checkTypeAnnotation(typeAnnotation: ts.TypeNode, name?: ts.Node) { if (typeAnnotation == null) { let ns = ""; if (name != null && name.kind === ts.SyntaxKind.Identifier) { ns = (name).text; } if (ns.charAt(0) === '_') return; - let failure = this.createFailure(location, 1, "expected " + ns + " to have a return type"); + let failure = this.createFailure(null, 1, "expected " + ns + " to have a return type"); this.addFailure(failure); } }