diff --git a/modules/angular2/src/common/forms/directives/ng_control.ts b/modules/angular2/src/common/forms/directives/ng_control.ts index b43bff5dc0..565e13561b 100644 --- a/modules/angular2/src/common/forms/directives/ng_control.ts +++ b/modules/angular2/src/common/forms/directives/ng_control.ts @@ -1,6 +1,7 @@ import {ControlValueAccessor} from './control_value_accessor'; import {AbstractControlDirective} from './abstract_control_directive'; import {unimplemented} from 'angular2/src/facade/exceptions'; +import {AsyncValidatorFn, ValidatorFn} from './validators'; /** * A base class that all control directive extend. @@ -12,8 +13,8 @@ export abstract class NgControl extends AbstractControlDirective { name: string = null; valueAccessor: ControlValueAccessor = null; - get validator(): Function { return unimplemented(); } - get asyncValidator(): Function { return unimplemented(); } + get validator(): ValidatorFn { return unimplemented(); } + get asyncValidator(): AsyncValidatorFn { return unimplemented(); } abstract viewToModelUpdate(newValue: any): void; } diff --git a/modules/angular2/src/common/forms/directives/ng_control_group.ts b/modules/angular2/src/common/forms/directives/ng_control_group.ts index 84d6fa04f4..31987a16de 100644 --- a/modules/angular2/src/common/forms/directives/ng_control_group.ts +++ b/modules/angular2/src/common/forms/directives/ng_control_group.ts @@ -16,7 +16,8 @@ import {ControlContainer} from './control_container'; import {controlPath, composeValidators, composeAsyncValidators} from './shared'; import {ControlGroup} from '../model'; import {Form} from './form_interface'; -import {Validators, NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators'; +import {NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators'; +import {AsyncValidatorFn, ValidatorFn} from './validators'; const controlGroupProvider = CONST_EXPR(new Provider(ControlContainer, {useExisting: forwardRef(() => NgControlGroup)})); @@ -106,7 +107,7 @@ export class NgControlGroup extends ControlContainer implements OnInit, */ get formDirective(): Form { return this._parent.formDirective; } - get validator(): Function { return composeValidators(this._validators); } + get validator(): ValidatorFn { return composeValidators(this._validators); } - get asyncValidator(): Function { return composeAsyncValidators(this._asyncValidators); } + get asyncValidator(): AsyncValidatorFn { return composeAsyncValidators(this._asyncValidators); } } diff --git a/modules/angular2/src/common/forms/directives/ng_control_name.ts b/modules/angular2/src/common/forms/directives/ng_control_name.ts index e54c847a0a..57493193fb 100644 --- a/modules/angular2/src/common/forms/directives/ng_control_name.ts +++ b/modules/angular2/src/common/forms/directives/ng_control_name.ts @@ -27,7 +27,8 @@ import { selectValueAccessor } from './shared'; import {Control} from '../model'; -import {Validators, NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators'; +import {NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators'; +import {ValidatorFn, AsyncValidatorFn} from './validators'; const controlNameBinding = @@ -136,9 +137,9 @@ export class NgControlName extends NgControl implements OnChanges, get formDirective(): any { return this._parent.formDirective; } - get validator(): Function { return composeValidators(this._validators); } + get validator(): ValidatorFn { return composeValidators(this._validators); } - get asyncValidator(): Function { return composeAsyncValidators(this._asyncValidators); } + get asyncValidator(): AsyncValidatorFn { return composeAsyncValidators(this._asyncValidators); } get control(): Control { return this.formDirective.getControl(this); } } diff --git a/modules/angular2/src/common/forms/directives/ng_form_control.ts b/modules/angular2/src/common/forms/directives/ng_form_control.ts index d68ea5fe8c..b69d0d9fb5 100644 --- a/modules/angular2/src/common/forms/directives/ng_form_control.ts +++ b/modules/angular2/src/common/forms/directives/ng_form_control.ts @@ -23,6 +23,7 @@ import { isPropertyUpdated, selectValueAccessor } from './shared'; +import {ValidatorFn, AsyncValidatorFn} from './validators'; const formControlBinding = CONST_EXPR(new Provider(NgControl, {useExisting: forwardRef(() => NgFormControl)})); @@ -110,9 +111,9 @@ export class NgFormControl extends NgControl implements OnChanges { get path(): string[] { return []; } - get validator(): Function { return composeValidators(this._validators); } + get validator(): ValidatorFn { return composeValidators(this._validators); } - get asyncValidator(): Function { return composeAsyncValidators(this._asyncValidators); } + get asyncValidator(): AsyncValidatorFn { return composeAsyncValidators(this._asyncValidators); } get control(): Control { return this.form; } diff --git a/modules/angular2/src/common/forms/directives/ng_model.ts b/modules/angular2/src/common/forms/directives/ng_model.ts index c353174883..4bcbb960df 100644 --- a/modules/angular2/src/common/forms/directives/ng_model.ts +++ b/modules/angular2/src/common/forms/directives/ng_model.ts @@ -3,7 +3,6 @@ import {EventEmitter, ObservableWrapper} from 'angular2/src/facade/async'; import { OnChanges, SimpleChange, - Query, Directive, forwardRef, Provider, @@ -14,7 +13,7 @@ import { import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor'; import {NgControl} from './ng_control'; import {Control} from '../model'; -import {Validators, NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators'; +import {NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators'; import { setUpControl, isPropertyUpdated, @@ -22,6 +21,7 @@ import { composeValidators, composeAsyncValidators } from './shared'; +import {ValidatorFn, AsyncValidatorFn} from './validators'; const formControlBinding = CONST_EXPR(new Provider(NgControl, {useExisting: forwardRef(() => NgModel)})); @@ -88,9 +88,9 @@ export class NgModel extends NgControl implements OnChanges { get path(): string[] { return []; } - get validator(): Function { return composeValidators(this._validators); } + get validator(): ValidatorFn { return composeValidators(this._validators); } - get asyncValidator(): Function { return composeAsyncValidators(this._asyncValidators); } + get asyncValidator(): AsyncValidatorFn { return composeAsyncValidators(this._asyncValidators); } viewToModelUpdate(newValue: any): void { this.viewModel = newValue; diff --git a/modules/angular2/src/common/forms/directives/normalize_validator.dart b/modules/angular2/src/common/forms/directives/normalize_validator.dart index 83049a9600..510abb3001 100644 --- a/modules/angular2/src/common/forms/directives/normalize_validator.dart +++ b/modules/angular2/src/common/forms/directives/normalize_validator.dart @@ -10,3 +10,11 @@ Function normalizeValidator(dynamic validator){ } } + +Function normalizeAsyncValidator(dynamic validator){ + if (validator is Validator) { + return (c) => validator.validate(c); + } else { + return validator; + } +} diff --git a/modules/angular2/src/common/forms/directives/normalize_validator.ts b/modules/angular2/src/common/forms/directives/normalize_validator.ts index 848d11c2b3..85e2ebdfbb 100644 --- a/modules/angular2/src/common/forms/directives/normalize_validator.ts +++ b/modules/angular2/src/common/forms/directives/normalize_validator.ts @@ -1,14 +1,18 @@ -import {Validator} from './validators'; -import {Control} from "../model"; +import {AbstractControl} from "../model"; +import {Validator, ValidatorFn, AsyncValidatorFn} from './validators'; -export type ctrlFunc = ((c: Control) => { - [key: string]: any -}); - -export function normalizeValidator(validator: (ctrlFunc | Validator)): ctrlFunc { +export function normalizeValidator(validator: ValidatorFn | Validator): ValidatorFn { if ((validator).validate !== undefined) { - return (c: Control) => (validator).validate(c); + return (c: AbstractControl) => (validator).validate(c); } else { - return validator; + return validator; + } +} + +export function normalizeAsyncValidator(validator: AsyncValidatorFn | Validator): AsyncValidatorFn { + if ((validator).validate !== undefined) { + return (c: AbstractControl) => Promise.resolve((validator).validate(c)); + } else { + return validator; } } diff --git a/modules/angular2/src/common/forms/directives/shared.ts b/modules/angular2/src/common/forms/directives/shared.ts index 86b346f346..d4b776dd4c 100644 --- a/modules/angular2/src/common/forms/directives/shared.ts +++ b/modules/angular2/src/common/forms/directives/shared.ts @@ -14,7 +14,8 @@ import {NumberValueAccessor} from './number_value_accessor'; import {CheckboxControlValueAccessor} from './checkbox_value_accessor'; import {SelectControlValueAccessor} from './select_control_value_accessor'; import {RadioControlValueAccessor} from './radio_control_value_accessor'; -import {normalizeValidator} from './normalize_validator'; +import {normalizeValidator, normalizeAsyncValidator} from './normalize_validator'; +import {ValidatorFn, AsyncValidatorFn} from './validators'; export function controlPath(name: string, parent: ControlContainer): string[] { @@ -56,13 +57,14 @@ function _throwError(dir: AbstractControlDirective, message: string): void { throw new BaseException(`${message} '${path}'`); } -export function composeValidators(validators: /* Array */ any[]): Function { +export function composeValidators(validators: /* Array */ any[]): ValidatorFn { return isPresent(validators) ? Validators.compose(validators.map(normalizeValidator)) : null; } export function composeAsyncValidators( - validators: /* Array */ any[]): Function { - return isPresent(validators) ? Validators.composeAsync(validators.map(normalizeValidator)) : null; + validators: /* Array */ any[]): AsyncValidatorFn { + return isPresent(validators) ? Validators.composeAsync(validators.map(normalizeAsyncValidator)) : + null; } export function isPropertyUpdated(changes: {[key: string]: any}, viewModel: any): boolean { diff --git a/modules/angular2/src/common/forms/directives/validators.ts b/modules/angular2/src/common/forms/directives/validators.ts index 36b725cd81..9851989045 100644 --- a/modules/angular2/src/common/forms/directives/validators.ts +++ b/modules/angular2/src/common/forms/directives/validators.ts @@ -1,11 +1,12 @@ -import {forwardRef, Provider, OpaqueToken, Attribute, Directive} from 'angular2/core'; +import {forwardRef, Provider, Attribute, Directive} from 'angular2/core'; import {CONST_EXPR} from 'angular2/src/facade/lang'; import {Validators, NG_VALIDATORS} from '../validators'; -import {Control} from '../model'; +import {AbstractControl} from '../model'; import * as modelModule from '../model'; import {NumberWrapper} from "angular2/src/facade/lang"; + /** * An interface that can be implemented by classes that can act as validators. * @@ -23,7 +24,7 @@ import {NumberWrapper} from "angular2/src/facade/lang"; * } * ``` */ -export interface Validator { validate(c: modelModule.Control): {[key: string]: any}; } +export interface Validator { validate(c: modelModule.AbstractControl): {[key: string]: any}; } const REQUIRED_VALIDATOR = CONST_EXPR(new Provider(NG_VALIDATORS, {useValue: Validators.required, multi: true})); @@ -45,6 +46,11 @@ const REQUIRED_VALIDATOR = export class RequiredValidator { } +export interface ValidatorFn { (c: AbstractControl): {[key: string]: any}; } +export interface AsyncValidatorFn { + (c: AbstractControl): any /*Promise<{[key: string]: any}>|Observable<{[key: string]: any}>*/; +} + /** * Provivder which adds {@link MinLengthValidator} to {@link NG_VALIDATORS}. * @@ -64,13 +70,13 @@ const MIN_LENGTH_VALIDATOR = CONST_EXPR( providers: [MIN_LENGTH_VALIDATOR] }) export class MinLengthValidator implements Validator { - private _validator: Function; + private _validator: ValidatorFn; constructor(@Attribute("minlength") minLength: string) { this._validator = Validators.minLength(NumberWrapper.parseInt(minLength, 10)); } - validate(c: Control): {[key: string]: any} { return this._validator(c); } + validate(c: AbstractControl): {[key: string]: any} { return this._validator(c); } } /** @@ -92,13 +98,13 @@ const MAX_LENGTH_VALIDATOR = CONST_EXPR( providers: [MAX_LENGTH_VALIDATOR] }) export class MaxLengthValidator implements Validator { - private _validator: Function; + private _validator: ValidatorFn; constructor(@Attribute("maxlength") maxLength: string) { this._validator = Validators.maxLength(NumberWrapper.parseInt(maxLength, 10)); } - validate(c: Control): {[key: string]: any} { return this._validator(c); } + validate(c: AbstractControl): {[key: string]: any} { return this._validator(c); } } @@ -121,11 +127,11 @@ const PATTERN_VALIDATOR = CONST_EXPR( providers: [PATTERN_VALIDATOR] }) export class PatternValidator implements Validator { - private _validator: Function; + private _validator: ValidatorFn; constructor(@Attribute("pattern") pattern: string) { this._validator = Validators.pattern(pattern); } - validate(c: Control): {[key: string]: any} { return this._validator(c); } + validate(c: AbstractControl): {[key: string]: any} { return this._validator(c); } } diff --git a/modules/angular2/src/common/forms/form_builder.ts b/modules/angular2/src/common/forms/form_builder.ts index f6bc0a13fe..960192eaa6 100644 --- a/modules/angular2/src/common/forms/form_builder.ts +++ b/modules/angular2/src/common/forms/form_builder.ts @@ -2,6 +2,7 @@ import {Injectable} from 'angular2/core'; import {StringMapWrapper} from 'angular2/src/facade/collection'; import {isPresent, isArray, CONST_EXPR, Type} from 'angular2/src/facade/lang'; import * as modelModule from './model'; +import {ValidatorFn, AsyncValidatorFn} from './directives/validators'; /** @@ -56,16 +57,18 @@ export class FormBuilder { group(controlsConfig: {[key: string]: any}, extra: {[key: string]: any} = null): modelModule.ControlGroup { var controls = this._reduceControls(controlsConfig); - var optionals = isPresent(extra) ? StringMapWrapper.get(extra, "optionals") : null; - var validator = isPresent(extra) ? StringMapWrapper.get(extra, "validator") : null; - var asyncValidator = isPresent(extra) ? StringMapWrapper.get(extra, "asyncValidator") : null; + var optionals = <{[key: string]: boolean}>( + isPresent(extra) ? StringMapWrapper.get(extra, "optionals") : null); + var validator: ValidatorFn = isPresent(extra) ? StringMapWrapper.get(extra, "validator") : null; + var asyncValidator: AsyncValidatorFn = + isPresent(extra) ? StringMapWrapper.get(extra, "asyncValidator") : null; return new modelModule.ControlGroup(controls, optionals, validator, asyncValidator); } /** * Construct a new {@link Control} with the given `value`,`validator`, and `asyncValidator`. */ - control(value: Object, validator: Function = null, - asyncValidator: Function = null): modelModule.Control { + control(value: Object, validator: ValidatorFn = null, + asyncValidator: AsyncValidatorFn = null): modelModule.Control { return new modelModule.Control(value, validator, asyncValidator); } @@ -73,8 +76,8 @@ export class FormBuilder { * Construct an array of {@link Control}s from the given `controlsConfig` array of * configuration, with the given optional `validator` and `asyncValidator`. */ - array(controlsConfig: any[], validator: Function = null, - asyncValidator: Function = null): modelModule.ControlArray { + array(controlsConfig: any[], validator: ValidatorFn = null, + asyncValidator: AsyncValidatorFn = null): modelModule.ControlArray { var controls = controlsConfig.map(c => this._createControl(c)); return new modelModule.ControlArray(controls, validator, asyncValidator); } @@ -98,12 +101,12 @@ export class FormBuilder { } else if (isArray(controlConfig)) { var value = controlConfig[0]; - var validator = controlConfig.length > 1 ? controlConfig[1] : null; - var asyncValidator = controlConfig.length > 2 ? controlConfig[2] : null; + var validator: ValidatorFn = controlConfig.length > 1 ? controlConfig[1] : null; + var asyncValidator: AsyncValidatorFn = controlConfig.length > 2 ? controlConfig[2] : null; return this.control(value, validator, asyncValidator); } else { return this.control(controlConfig); } } -} \ No newline at end of file +} diff --git a/modules/angular2/src/common/forms/model.ts b/modules/angular2/src/common/forms/model.ts index 40850fe3c6..3654580838 100644 --- a/modules/angular2/src/common/forms/model.ts +++ b/modules/angular2/src/common/forms/model.ts @@ -1,7 +1,8 @@ -import {StringWrapper, isPresent, isBlank, normalizeBool} from 'angular2/src/facade/lang'; +import {isPresent, isBlank, normalizeBool} from 'angular2/src/facade/lang'; import {Observable, EventEmitter, ObservableWrapper} from 'angular2/src/facade/async'; import {PromiseWrapper} from 'angular2/src/facade/promise'; import {StringMapWrapper, ListWrapper} from 'angular2/src/facade/collection'; +import {ValidatorFn, AsyncValidatorFn} from './directives/validators'; /** * Indicates that a Control is valid, i.e. that no errors exist in the input value. @@ -64,7 +65,7 @@ export abstract class AbstractControl { private _parent: ControlGroup | ControlArray; private _asyncValidationSubscription: any; - constructor(public validator: Function, public asyncValidator: Function) {} + constructor(public validator: ValidatorFn, public asyncValidator: AsyncValidatorFn) {} get value(): any { return this._value; } @@ -137,15 +138,17 @@ export abstract class AbstractControl { } } - private _runValidator() { return isPresent(this.validator) ? this.validator(this) : null; } + private _runValidator(): {[key: string]: any} { + return isPresent(this.validator) ? this.validator(this) : null; + } private _runAsyncValidator(emitEvent: boolean): void { if (isPresent(this.asyncValidator)) { this._status = PENDING; this._cancelExistingSubscription(); var obs = toObservable(this.asyncValidator(this)); - this._asyncValidationSubscription = - ObservableWrapper.subscribe(obs, res => this.setErrors(res, {emitEvent: emitEvent})); + this._asyncValidationSubscription = ObservableWrapper.subscribe( + obs, (res: {[key: string]: any}) => this.setErrors(res, {emitEvent: emitEvent})); } } @@ -268,7 +271,8 @@ export class Control extends AbstractControl { /** @internal */ _onChange: Function; - constructor(value: any = null, validator: Function = null, asyncValidator: Function = null) { + constructor(value: any = null, validator: ValidatorFn = null, + asyncValidator: AsyncValidatorFn = null) { super(validator, asyncValidator); this._value = value; this.updateValueAndValidity({onlySelf: true, emitEvent: false}); @@ -331,8 +335,8 @@ export class ControlGroup extends AbstractControl { private _optionals: {[key: string]: boolean}; constructor(public controls: {[key: string]: AbstractControl}, - optionals: {[key: string]: boolean} = null, validator: Function = null, - asyncValidator: Function = null) { + optionals: {[key: string]: boolean} = null, validator: ValidatorFn = null, + asyncValidator: AsyncValidatorFn = null) { super(validator, asyncValidator); this._optionals = isPresent(optionals) ? optionals : {}; this._initObservables(); @@ -444,8 +448,8 @@ export class ControlGroup extends AbstractControl { * ### Example ([live demo](http://plnkr.co/edit/23DESOpbNnBpBHZt1BR4?p=preview)) */ export class ControlArray extends AbstractControl { - constructor(public controls: AbstractControl[], validator: Function = null, - asyncValidator: Function = null) { + constructor(public controls: AbstractControl[], validator: ValidatorFn = null, + asyncValidator: AsyncValidatorFn = null) { super(validator, asyncValidator); this._initObservables(); this._setParentForControls(); diff --git a/modules/angular2/src/common/forms/validators.ts b/modules/angular2/src/common/forms/validators.ts index 7abe20b1b1..7663b7263e 100644 --- a/modules/angular2/src/common/forms/validators.ts +++ b/modules/angular2/src/common/forms/validators.ts @@ -5,6 +5,7 @@ import {ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection'; import {OpaqueToken} from 'angular2/core'; import * as modelModule from './model'; +import {ValidatorFn, AsyncValidatorFn} from './directives/validators'; /** * Providers for validators to be used for {@link Control}s in a form. @@ -43,7 +44,7 @@ export class Validators { /** * Validator that requires controls to have a non-empty value. */ - static required(control: modelModule.Control): {[key: string]: boolean} { + static required(control: modelModule.AbstractControl): {[key: string]: boolean} { return isBlank(control.value) || (isString(control.value) && control.value == "") ? {"required": true} : null; @@ -52,8 +53,8 @@ export class Validators { /** * Validator that requires controls to have a value of a minimum length. */ - static minLength(minLength: number): Function { - return (control: modelModule.Control): {[key: string]: any} => { + static minLength(minLength: number): ValidatorFn { + return (control: modelModule.AbstractControl): {[key: string]: any} => { if (isPresent(Validators.required(control))) return null; var v: string = control.value; return v.length < minLength ? @@ -65,8 +66,8 @@ export class Validators { /** * Validator that requires controls to have a value of a maximum length. */ - static maxLength(maxLength: number): Function { - return (control: modelModule.Control): {[key: string]: any} => { + static maxLength(maxLength: number): ValidatorFn { + return (control: modelModule.AbstractControl): {[key: string]: any} => { if (isPresent(Validators.required(control))) return null; var v: string = control.value; return v.length > maxLength ? @@ -78,8 +79,8 @@ export class Validators { /** * Validator that requires a control to match a regex to its value. */ - static pattern(pattern: string): Function { - return (control: modelModule.Control): {[key: string]: any} => { + static pattern(pattern: string): ValidatorFn { + return (control: modelModule.AbstractControl): {[key: string]: any} => { if (isPresent(Validators.required(control))) return null; let regex = new RegExp(`^${pattern}$`); let v: string = control.value; @@ -91,13 +92,13 @@ export class Validators { /** * No-op validator. */ - static nullValidator(c: any): {[key: string]: boolean} { return null; } + static nullValidator(c: modelModule.AbstractControl): {[key: string]: boolean} { return null; } /** * Compose multiple validators into a single function that returns the union * of the individual error maps. */ - static compose(validators: Function[]): Function { + static compose(validators: ValidatorFn[]): ValidatorFn { if (isBlank(validators)) return null; var presentValidators = validators.filter(isPresent); if (presentValidators.length == 0) return null; @@ -107,13 +108,13 @@ export class Validators { }; } - static composeAsync(validators: Function[]): Function { + static composeAsync(validators: AsyncValidatorFn[]): AsyncValidatorFn { if (isBlank(validators)) return null; var presentValidators = validators.filter(isPresent); if (presentValidators.length == 0) return null; return function(control: modelModule.AbstractControl) { - let promises = _executeValidators(control, presentValidators).map(_convertToPromise); + let promises = _executeAsyncValidators(control, presentValidators).map(_convertToPromise); return PromiseWrapper.all(promises).then(_mergeErrors); }; } @@ -123,13 +124,20 @@ function _convertToPromise(obj: any): any { return PromiseWrapper.isPromise(obj) ? obj : ObservableWrapper.toPromise(obj); } -function _executeValidators(control: modelModule.AbstractControl, validators: Function[]): any[] { +function _executeValidators(control: modelModule.AbstractControl, + validators: ValidatorFn[]): any[] { + return validators.map(v => v(control)); +} + +function _executeAsyncValidators(control: modelModule.AbstractControl, + validators: AsyncValidatorFn[]): any[] { return validators.map(v => v(control)); } function _mergeErrors(arrayOfErrors: any[]): {[key: string]: any} { - var res = arrayOfErrors.reduce((res, errors) => { - return isPresent(errors) ? StringMapWrapper.merge(res, errors) : res; - }, {}); + var res: {[key: string]: any} = + arrayOfErrors.reduce((res: {[key: string]: any}, errors: {[key: string]: any}) => { + return isPresent(errors) ? StringMapWrapper.merge(res, errors) : res; + }, {}); return StringMapWrapper.isEmpty(res) ? null : res; } diff --git a/modules/angular2/src/common/pipes/async_pipe.ts b/modules/angular2/src/common/pipes/async_pipe.ts index ee27a94aa5..9131cfb147 100644 --- a/modules/angular2/src/common/pipes/async_pipe.ts +++ b/modules/angular2/src/common/pipes/async_pipe.ts @@ -22,7 +22,7 @@ class ObservableStrategy { } class PromiseStrategy { - createSubscription(async: any, updateLatestValue: any): any { + createSubscription(async: Promise, updateLatestValue: (v: any) => any): any { return async.then(updateLatestValue); } diff --git a/modules/angular2/src/common/pipes/i18n_plural_pipe.ts b/modules/angular2/src/common/pipes/i18n_plural_pipe.ts index 8cf45e82dc..0501441e3a 100644 --- a/modules/angular2/src/common/pipes/i18n_plural_pipe.ts +++ b/modules/angular2/src/common/pipes/i18n_plural_pipe.ts @@ -48,7 +48,7 @@ export class I18nPluralPipe implements PipeTransform { transform(value: number, args: any[] = null): string { var key: string; var valueStr: string; - var pluralMap: {[count: string]: string} = args[0]; + var pluralMap: {[count: string]: string} = <{[count: string]: string}>(args[0]); if (!isStringMap(pluralMap)) { throw new InvalidPipeArgumentException(I18nPluralPipe, pluralMap); diff --git a/modules/angular2/src/common/pipes/i18n_select_pipe.ts b/modules/angular2/src/common/pipes/i18n_select_pipe.ts index 619b38c9dc..04722d657f 100644 --- a/modules/angular2/src/common/pipes/i18n_select_pipe.ts +++ b/modules/angular2/src/common/pipes/i18n_select_pipe.ts @@ -37,7 +37,7 @@ import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception'; @Injectable() export class I18nSelectPipe implements PipeTransform { transform(value: string, args: any[] = null): string { - var mapping: {[key: string]: string} = args[0]; + var mapping: {[key: string]: string} = <{[count: string]: string}>(args[0]); if (!isStringMap(mapping)) { throw new InvalidPipeArgumentException(I18nSelectPipe, mapping); } diff --git a/modules/angular2/src/compiler/change_definition_factory.ts b/modules/angular2/src/compiler/change_definition_factory.ts index de12f8cbcd..51b8f61263 100644 --- a/modules/angular2/src/compiler/change_definition_factory.ts +++ b/modules/angular2/src/compiler/change_definition_factory.ts @@ -146,8 +146,9 @@ class ProtoViewVisitor implements TemplateAstVisitor { var directiveIndex = new DirectiveIndex(this.boundElementCount - 1, directiveIndexAsNumber); var directiveMetadata = ast.directive; var outputsArray = []; - StringMapWrapper.forEach(ast.directive.outputs, (eventName, dirProperty) => outputsArray.push( - [dirProperty, eventName])); + StringMapWrapper.forEach( + ast.directive.outputs, + (eventName: string, dirProperty: string) => outputsArray.push([dirProperty, eventName])); var directiveRecord = new DirectiveRecord({ directiveIndex: directiveIndex, callAfterContentInit: diff --git a/modules/angular2/src/compiler/directive_metadata.ts b/modules/angular2/src/compiler/directive_metadata.ts index 360acf64bd..bf5c08ea27 100644 --- a/modules/angular2/src/compiler/directive_metadata.ts +++ b/modules/angular2/src/compiler/directive_metadata.ts @@ -31,7 +31,7 @@ export abstract class CompileMetadataWithIdentifier { abstract toJson(): {[key: string]: any}; - get identifier(): CompileIdentifierMetadata { return unimplemented(); } + get identifier(): CompileIdentifierMetadata { return unimplemented(); } } export abstract class CompileMetadataWithType extends CompileMetadataWithIdentifier { @@ -41,9 +41,9 @@ export abstract class CompileMetadataWithType extends CompileMetadataWithIdentif abstract toJson(): {[key: string]: any}; - get type(): CompileTypeMetadata { return unimplemented(); } + get type(): CompileTypeMetadata { return unimplemented(); } - get identifier(): CompileIdentifierMetadata { return unimplemented(); } + get identifier(): CompileIdentifierMetadata { return unimplemented(); } } export class CompileIdentifierMetadata implements CompileMetadataWithIdentifier { @@ -628,4 +628,4 @@ function objFromJson(obj: any, fn: (a: {[key: string]: any}) => any): any { function objToJson(obj: any): string | {[key: string]: any} { return (isString(obj) || isBlank(obj)) ? obj : obj.toJson(); -} \ No newline at end of file +} diff --git a/modules/angular2/src/compiler/proto_view_compiler.ts b/modules/angular2/src/compiler/proto_view_compiler.ts index 9b211391bc..68f489505c 100644 --- a/modules/angular2/src/compiler/proto_view_compiler.ts +++ b/modules/angular2/src/compiler/proto_view_compiler.ts @@ -234,7 +234,7 @@ class ProtoViewBuilderVisitor implement attrAsts: TemplateAst[]): string[][] { var attrs = visitAndReturnContext(this, attrAsts, {}); directives.forEach(directiveMeta => { - StringMapWrapper.forEach(directiveMeta.hostAttributes, (value, name) => { + StringMapWrapper.forEach(directiveMeta.hostAttributes, (value: string, name: string) => { var prevValue = attrs[name]; attrs[name] = isPresent(prevValue) ? mergeAttributeValue(name, prevValue, value) : value; }); @@ -330,12 +330,14 @@ class ProtoViewBuilderVisitor implement } function mapToKeyValueArray(data: {[key: string]: string}): string[][] { - var entryArray = []; - StringMapWrapper.forEach(data, (value, name) => { entryArray.push([name, value]); }); + var entryArray: string[][] = []; + StringMapWrapper.forEach(data, + (value: string, name: string) => { entryArray.push([name, value]); }); // We need to sort to get a defined output order // for tests and for caching generated artifacts... - ListWrapper.sort(entryArray, (entry1, entry2) => StringWrapper.compare(entry1[0], entry2[0])); - var keyValueArray = []; + ListWrapper.sort(entryArray, (entry1: string[], entry2: string[]) => + StringWrapper.compare(entry1[0], entry2[0])); + var keyValueArray: string[][] = []; entryArray.forEach((entry) => { keyValueArray.push([entry[0], entry[1]]); }); return keyValueArray; } diff --git a/modules/angular2/src/compiler/style_compiler.ts b/modules/angular2/src/compiler/style_compiler.ts index 0d69cad2e0..565e33c0c6 100644 --- a/modules/angular2/src/compiler/style_compiler.ts +++ b/modules/angular2/src/compiler/style_compiler.ts @@ -53,9 +53,9 @@ export class StyleCompiler { private _loadStyles(plainStyles: string[], absUrls: string[], encapsulate: boolean): Promise> { - var promises = absUrls.map((absUrl) => { + var promises: Promise[] = absUrls.map((absUrl: string): Promise => { var cacheKey = `${absUrl}${encapsulate ? '.shim' : ''}`; - var result = this._styleCache.get(cacheKey); + var result: Promise = this._styleCache.get(cacheKey); if (isBlank(result)) { result = this._xhr.get(absUrl).then((style) => { var styleWithImports = extractStyleUrls(this._urlResolver, absUrl, style); @@ -66,7 +66,7 @@ export class StyleCompiler { } return result; }); - return PromiseWrapper.all(promises).then((nestedStyles: string[][]) => { + return PromiseWrapper.all(promises).then((nestedStyles: string[][]) => { var result: Array = plainStyles.map(plainStyle => this._shimIfNeeded(plainStyle, encapsulate)); nestedStyles.forEach(styles => result.push(styles)); diff --git a/modules/angular2/src/compiler/template_parser.ts b/modules/angular2/src/compiler/template_parser.ts index d6107d8341..f86065433a 100644 --- a/modules/angular2/src/compiler/template_parser.ts +++ b/modules/angular2/src/compiler/template_parser.ts @@ -505,7 +505,7 @@ class TemplateParseVisitor implements HtmlAstVisitor { sourceSpan: ParseSourceSpan, targetPropertyAsts: BoundElementPropertyAst[]) { if (isPresent(hostProps)) { - StringMapWrapper.forEach(hostProps, (expression, propName) => { + StringMapWrapper.forEach(hostProps, (expression: string, propName: string) => { var exprAst = this._parseBinding(expression, sourceSpan); targetPropertyAsts.push( this._createElementPropertyAst(elementName, propName, exprAst, sourceSpan)); @@ -517,7 +517,7 @@ class TemplateParseVisitor implements HtmlAstVisitor { sourceSpan: ParseSourceSpan, targetEventAsts: BoundEventAst[]) { if (isPresent(hostListeners)) { - StringMapWrapper.forEach(hostListeners, (expression, propName) => { + StringMapWrapper.forEach(hostListeners, (expression: string, propName: string) => { this._parseEvent(propName, expression, sourceSpan, [], targetEventAsts); }); } @@ -645,7 +645,7 @@ class TemplateParseVisitor implements HtmlAstVisitor { var allDirectiveEvents = new Set(); directives.forEach(directive => { StringMapWrapper.forEach(directive.directive.outputs, - (eventName, _) => { allDirectiveEvents.add(eventName); }); + (eventName: string, _) => { allDirectiveEvents.add(eventName); }); }); events.forEach(event => { if (isPresent(event.target) || !SetWrapper.has(allDirectiveEvents, event.name)) { diff --git a/modules/angular2/src/core/application_ref.ts b/modules/angular2/src/core/application_ref.ts index c960e8bd33..54b1a00d49 100644 --- a/modules/angular2/src/core/application_ref.ts +++ b/modules/angular2/src/core/application_ref.ts @@ -128,7 +128,7 @@ function _createPlatform(providers?: Array): PlatformRe } function _runPlatformInitializers(injector: Injector): void { - let inits: Function[] = injector.getOptional(PLATFORM_INITIALIZER); + let inits: Function[] = injector.getOptional(PLATFORM_INITIALIZER); if (isPresent(inits)) inits.forEach(init => init()); } @@ -150,7 +150,7 @@ export abstract class PlatformRef { * Retrieve the platform {@link Injector}, which is the parent injector for * every Angular application on the page and provides singleton providers. */ - get injector(): Injector { return unimplemented(); }; + get injector(): Injector { throw unimplemented(); }; /** * Instantiate a new Angular application on the page. @@ -222,7 +222,7 @@ export class PlatformRef_ extends PlatformRef { asyncApplication(bindingFn: (zone: NgZone) => Promise>, additionalProviders?: Array): Promise { var zone = createNgZone(); - var completer = PromiseWrapper.completer(); + var completer = PromiseWrapper.completer(); if (bindingFn === null) { completer.resolve(this._initApp(zone, additionalProviders)); } else { @@ -342,12 +342,12 @@ export abstract class ApplicationRef { /** * Retrieve the application {@link Injector}. */ - get injector(): Injector { return unimplemented(); }; + get injector(): Injector { return unimplemented(); }; /** * Retrieve the application {@link NgZone}. */ - get zone(): NgZone { return unimplemented(); }; + get zone(): NgZone { return unimplemented(); }; /** * Dispose of this application and all of its components. @@ -369,7 +369,7 @@ export abstract class ApplicationRef { /** * Get a list of component types registered to this application. */ - get componentTypes(): Type[] { return unimplemented(); }; + get componentTypes(): Type[] { return unimplemented(); }; } export class ApplicationRef_ extends ApplicationRef { @@ -449,13 +449,13 @@ export class ApplicationRef_ extends ApplicationRef { completer.reject(e, e.stack); } }); - return completer.promise.then(_ => { + return completer.promise.then((ref: ComponentRef) => { let c = this._injector.get(Console); if (assertionsEnabled()) { c.log( "Angular 2 is running in the development mode. Call enableProdMode() to enable the production mode."); } - return _; + return ref; }); } diff --git a/modules/angular2/src/core/change_detection/proto_change_detector.ts b/modules/angular2/src/core/change_detection/proto_change_detector.ts index ee0016a9df..2f2d7c22cd 100644 --- a/modules/angular2/src/core/change_detection/proto_change_detector.ts +++ b/modules/angular2/src/core/change_detection/proto_change_detector.ts @@ -64,8 +64,9 @@ export class DynamicProtoChangeDetector implements ProtoChangeDetector { export function createPropertyRecords(definition: ChangeDetectorDefinition): ProtoRecord[] { var recordBuilder = new ProtoRecordBuilder(); - ListWrapper.forEachWithIndex(definition.bindingRecords, - (b, index) => recordBuilder.add(b, definition.variableNames, index)); + ListWrapper.forEachWithIndex( + definition.bindingRecords, + (b: BindingRecord, index: number) => recordBuilder.add(b, definition.variableNames, index)); return coalesce(recordBuilder.records); } diff --git a/modules/angular2/src/core/debug/debug_node.ts b/modules/angular2/src/core/debug/debug_node.ts index 88918f69d2..87634f09d3 100644 --- a/modules/angular2/src/core/debug/debug_node.ts +++ b/modules/angular2/src/core/debug/debug_node.ts @@ -91,19 +91,19 @@ export class DebugElement extends DebugNode { } queryAll(predicate: Predicate): DebugElement[] { - var matches = []; + var matches: DebugElement[] = []; _queryElementChildren(this, predicate, matches); return matches; } queryAllNodes(predicate: Predicate): DebugNode[] { - var matches = []; + var matches: DebugNode[] = []; _queryNodeChildren(this, predicate, matches); return matches; } get children(): DebugElement[] { - var children = []; + var children: DebugElement[] = []; this.childNodes.forEach((node) => { if (node instanceof DebugElement) { children.push(node); diff --git a/modules/angular2/src/core/debug/debug_renderer.ts b/modules/angular2/src/core/debug/debug_renderer.ts index 22c9e67245..955f610fee 100644 --- a/modules/angular2/src/core/debug/debug_renderer.ts +++ b/modules/angular2/src/core/debug/debug_renderer.ts @@ -73,7 +73,7 @@ export class DebugDomRenderer implements Renderer { if (isPresent(debugNode)) { var debugParent = debugNode.parent; if (viewRootNodes.length > 0 && isPresent(debugParent)) { - var debugViewRootNodes = []; + var debugViewRootNodes: DebugNode[] = []; viewRootNodes.forEach((rootNode) => debugViewRootNodes.push(getDebugNode(rootNode))); debugParent.insertChildrenAfter(debugNode, debugViewRootNodes); } diff --git a/modules/angular2/src/core/di/provider.ts b/modules/angular2/src/core/di/provider.ts index 753f0fd4d8..f8fb22f735 100644 --- a/modules/angular2/src/core/di/provider.ts +++ b/modules/angular2/src/core/di/provider.ts @@ -513,7 +513,7 @@ export class ProviderBuilder { */ export function resolveFactory(provider: Provider): ResolvedFactory { var factoryFn: Function; - var resolvedDeps; + var resolvedDeps: Dependency[]; if (isPresent(provider.useClass)) { var useClass = resolveForwardRef(provider.useClass); factoryFn = reflector.factory(useClass); @@ -619,7 +619,7 @@ function _constructDependencies(factoryFunction: Function, dependencies: any[]): } function _dependenciesFor(typeOrFunc): Dependency[] { - var params = reflector.parameters(typeOrFunc); + var params: any[][] = reflector.parameters(typeOrFunc); if (isBlank(params)) return []; if (params.some(isBlank)) { throw new NoAnnotationError(typeOrFunc, params); diff --git a/modules/angular2/src/core/linker/view.ts b/modules/angular2/src/core/linker/view.ts index e245815f7a..ca446dbdf2 100644 --- a/modules/angular2/src/core/linker/view.ts +++ b/modules/angular2/src/core/linker/view.ts @@ -115,8 +115,9 @@ export class AppView implements ChangeDispatcher { this.disposables = disposables; this.appElements = appElements; var localsMap = new Map(); - StringMapWrapper.forEach(this.proto.templateVariableBindings, - (templateName, _) => { localsMap.set(templateName, null); }); + StringMapWrapper.forEach( + this.proto.templateVariableBindings, + (templateName: string, _: string) => { localsMap.set(templateName, null); }); for (var i = 0; i < appElements.length; i++) { var appEl = appElements[i]; var providerTokens = []; @@ -125,13 +126,14 @@ export class AppView implements ChangeDispatcher { providerTokens.push(appEl.proto.protoInjector.getProviderAtIndex(j).key.token); } } - StringMapWrapper.forEach(appEl.proto.directiveVariableBindings, (directiveIndex, name) => { - if (isBlank(directiveIndex)) { - localsMap.set(name, appEl.nativeElement); - } else { - localsMap.set(name, appEl.getDirectiveAtIndex(directiveIndex)); - } - }); + StringMapWrapper.forEach(appEl.proto.directiveVariableBindings, + (directiveIndex: number, name: string) => { + if (isBlank(directiveIndex)) { + localsMap.set(name, appEl.nativeElement); + } else { + localsMap.set(name, appEl.getDirectiveAtIndex(directiveIndex)); + } + }); this.renderer.setElementDebugInfo( appEl.nativeElement, new RenderDebugInfo(appEl.getInjector(), appEl.getComponent(), providerTokens, localsMap)); diff --git a/modules/angular2/src/core/linker/view_container_ref.ts b/modules/angular2/src/core/linker/view_container_ref.ts index 3048c8a6f0..759c38d3cc 100644 --- a/modules/angular2/src/core/linker/view_container_ref.ts +++ b/modules/angular2/src/core/linker/view_container_ref.ts @@ -41,7 +41,7 @@ export abstract class ViewContainerRef { * Anchor element that specifies the location of this container in the containing View. * */ - get element(): ElementRef { return unimplemented(); } + get element(): ElementRef { return unimplemented(); } /** * Destroys all Views in this container. @@ -60,7 +60,7 @@ export abstract class ViewContainerRef { /** * Returns the number of Views currently attached to this container. */ - get length(): number { return unimplemented(); }; + get length(): number { return unimplemented(); }; /** * Instantiates an Embedded View based on the {@link TemplateRef `templateRef`} and inserts it diff --git a/modules/angular2/src/core/linker/view_ref.ts b/modules/angular2/src/core/linker/view_ref.ts index 8e823ce380..7d6638fa5b 100644 --- a/modules/angular2/src/core/linker/view_ref.ts +++ b/modules/angular2/src/core/linker/view_ref.ts @@ -6,9 +6,9 @@ export abstract class ViewRef { /** * @internal */ - get changeDetectorRef(): ChangeDetectorRef { return unimplemented(); }; + get changeDetectorRef(): ChangeDetectorRef { return unimplemented(); }; - get destroyed(): boolean { return unimplemented(); } + get destroyed(): boolean { return unimplemented(); } } /** @@ -21,7 +21,7 @@ export abstract class ViewRef { * {@link AppViewManager#createHostViewInContainer}, {@link ViewContainerRef#createHostView}. */ export abstract class HostViewRef extends ViewRef { - get rootNodes(): any[] { return unimplemented(); }; + get rootNodes(): any[] { return unimplemented(); }; } /** @@ -88,7 +88,7 @@ export abstract class EmbeddedViewRef extends ViewRef { */ abstract hasLocal(variableName: string): boolean; - get rootNodes(): any[] { return unimplemented(); }; + get rootNodes(): any[] { return unimplemented(); }; } export class ViewRef_ implements EmbeddedViewRef, HostViewRef { @@ -116,4 +116,4 @@ export class HostViewFactoryRef_ implements HostViewFactoryRef { constructor(private _hostViewFactory: HostViewFactory) {} get internalHostViewFactory(): HostViewFactory { return this._hostViewFactory; } -} \ No newline at end of file +} diff --git a/modules/angular2/src/core/reflection/reflector.ts b/modules/angular2/src/core/reflection/reflector.ts index 908b993dc9..94b472ef7b 100644 --- a/modules/angular2/src/core/reflection/reflector.ts +++ b/modules/angular2/src/core/reflection/reflector.ts @@ -87,7 +87,7 @@ export class Reflector { } } - parameters(typeOrFunc: /*Type*/ any): any[] { + parameters(typeOrFunc: /*Type*/ any): any[][] { if (this._injectableInfo.has(typeOrFunc)) { var res = this._getReflectionInfo(typeOrFunc).parameters; return isPresent(res) ? res : []; @@ -148,7 +148,7 @@ export class Reflector { } /** @internal */ - _getReflectionInfo(typeOrFunc: any) { + _getReflectionInfo(typeOrFunc: any): ReflectionInfo { if (isPresent(this._usedKeys)) { this._usedKeys.add(typeOrFunc); } diff --git a/modules/angular2/src/facade/async.dart b/modules/angular2/src/facade/async.dart index b34d47a13a..899a411b99 100644 --- a/modules/angular2/src/facade/async.dart +++ b/modules/angular2/src/facade/async.dart @@ -25,7 +25,7 @@ class TimerWrapper { } class ObservableWrapper { - static StreamSubscription subscribe(Stream s, Function onNext, + static StreamSubscription subscribe/**/(Stream s, onNext(/*=T*/ value), [onError, onComplete]) { return s.listen(onNext, onError: onError, onDone: onComplete, cancelOnError: true); diff --git a/modules/angular2/src/facade/async.ts b/modules/angular2/src/facade/async.ts index d8a902a736..81d2a3308a 100644 --- a/modules/angular2/src/facade/async.ts +++ b/modules/angular2/src/facade/async.ts @@ -1,10 +1,8 @@ -import {global, isPresent, noop} from 'angular2/src/facade/lang'; +import {global, noop} from 'angular2/src/facade/lang'; export {PromiseWrapper, PromiseCompleter} from 'angular2/src/facade/promise'; import {Observable} from 'rxjs/Observable'; import {Subject} from 'rxjs/Subject'; -import {Subscription} from 'rxjs/Subscription'; -import {Operator} from 'rxjs/Operator'; import {PromiseObservable} from 'rxjs/observable/PromiseObservable'; import {toPromise} from 'rxjs/operator/toPromise'; diff --git a/modules/angular2/src/facade/collection.dart b/modules/angular2/src/facade/collection.dart index 3bf0eb1e52..8e7277f60b 100644 --- a/modules/angular2/src/facade/collection.dart +++ b/modules/angular2/src/facade/collection.dart @@ -33,15 +33,15 @@ class IterableMap extends IterableBase { } class MapWrapper { - static Map clone(Map m) => new Map.from(m); + static Map/**/ clone/**/(Map/**/ m) => new Map.from(m); // in opposite to JS, Dart does not create a new map - static Map createFromStringMap(Map m) => m; + static Map/**/ createFromStringMap/**/(Map/**/ m) => m; // in opposite to JS, Dart does not create a new map - static Map toStringMap(Map m) => m; + static Map/**/ toStringMap/**/(Map/**/ m) => m; - static Map createFromPairs(List pairs) => pairs.fold({}, (m, p) { + static Map/**/ createFromPairs/**/(List pairs) => pairs.fold(/**/{}, (m, p) { m[p[0]] = p[1]; return m; }); @@ -52,29 +52,29 @@ class MapWrapper { } } - static Iterable iterable(Map m) => new IterableMap(m); - static List keys(Map m) => m.keys.toList(); - static List values(Map m) => m.values.toList(); + static Iterable/*>*/ iterable/**/(Map/**/ m) => new IterableMap(m); + static List/**/ keys/**/(Map/**/ m) => m.keys.toList(); + static List/**/ values/**/(Map/**/ m) => m.values.toList(); } class StringMapWrapper { - static Map create() => {}; - static bool contains(Map map, key) => map.containsKey(key); - static get(Map map, key) => map[key]; - static void set(Map map, key, value) { + static Map/**/ create/**/() => {}; + static bool contains/**/(Map/**/ map, String key) => map.containsKey(key); + static get/**/(Map/**/ map, String key) => map[key]; + static void set/**/(Map/**/ map, String key, /*=V*/value) { map[key] = value; } - static void delete(Map m, k) { + static void delete/**/(Map/**/ m, String k) { m.remove(k); } - static void forEach(Map m, fn(v, k)) { + static void forEach/**/(Map/**/ m, fn(/*=V*/ v, String k)) { m.forEach((k, v) => fn(v, k)); } - static Map merge(Map a, Map b) { - var m = new Map.from(a); + static Map/**/ merge/**/(Map/**/ a, Map/**/ b) { + var m = new Map/**/.from(a); if (b != null) { b.forEach((k, v) => m[k] = v); } @@ -86,7 +86,7 @@ class StringMapWrapper { } static bool isEmpty(Map m) => m.isEmpty; - static bool equals(Map m1, Map m2) { + static bool equals/**/(Map/**/ m1, Map/**/ m2) { if (m1.length != m2.length) { return false; } @@ -102,9 +102,9 @@ class StringMapWrapper { typedef bool Predicate(T item); class ListWrapper { - static List clone(Iterable l) => new List.from(l); - static List createFixedSize(int size) => new List(size); - static List createGrowableSize(int size) => + static List/**/ clone/**/(Iterable/**/ l) => new List.from(l); + static List/**/ createFixedSize/**/(int size) => new List(size); + static List/**/ createGrowableSize/**/(int size) => new List.generate(size, (_) => null, growable: true); static UnmodifiableListView createImmutable(List input) { return new UnmodifiableListView(input); @@ -116,43 +116,43 @@ class ListWrapper { static int lastIndexOf(List list, value, [int startIndex = null]) => list.lastIndexOf(value, startIndex == null ? list.length : startIndex); - static void forEachWithIndex(List list, fn(item, index)) { + static void forEachWithIndex/**/(List/**/ list, fn(/*=T*/ item, int index)) { for (var i = 0; i < list.length; ++i) { fn(list[i], i); } } - static first(List list) => list.isEmpty ? null : list.first; - static last(List list) => list.isEmpty ? null : list.last; - static List reversed(List list) => list.reversed.toList(); - static List concat(List a, List b) { + static /*=T*/ first/**/(List/**/ list) => list.isEmpty ? null : list.first; + static /*=T*/ last/**/(List/**/ list) => list.isEmpty ? null : list.last; + static List/**/ reversed/**/(List/**/ list) => list.reversed.toList(); + static List/**/ concat/**/(List/**/ a, List/**/ b) { return new List() ..length = a.length + b.length ..setRange(0, a.length, a) ..setRange(a.length, a.length + b.length, b); } - static void insert(List l, int index, value) { + static void insert/**/(List/**/ l, int index, /*=T*/ value) { l.insert(index, value); } static removeAt(List l, int index) => l.removeAt(index); - static void removeAll(List list, List items) { + static void removeAll/**/(List/**/ list, List/**/ items) { for (var i = 0; i < items.length; ++i) { list.remove(items[i]); } } - static bool remove(List list, item) => list.remove(item); + static bool remove/**/(List/**/ list, /*=T*/ item) => list.remove(item); static void clear(List l) { l.clear(); } static bool isEmpty(Iterable list) => list.isEmpty; - static void fill(List l, value, [int start = 0, int end]) { + static void fill/**/(List/**/ l, /*=T*/ value, [int start = 0, int end]) { l.fillRange(_startOffset(l, start), _endOffset(l, end), value); } - static bool equals(List a, List b) { + static bool equals/**/(List/**/ a, List/**/ b) { if (a.length != b.length) return false; for (var i = 0; i < a.length; ++i) { if (a[i] != b[i]) return false; @@ -160,7 +160,7 @@ class ListWrapper { return true; } - static List slice(List l, [int from = 0, int to]) { + static List/**/ slice/**/(List/**/ l, [int from = 0, int to]) { from = _startOffset(l, from); to = _endOffset(l, to); //in JS if from > to an empty array is returned @@ -170,7 +170,7 @@ class ListWrapper { return l.sublist(from, to); } - static List splice(List l, int from, int length) { + static List/**/ splice/**/(List/**/ l, int from, int length) { from = _startOffset(l, from); var to = from + length; var sub = l.sublist(from, to); @@ -178,7 +178,7 @@ class ListWrapper { return sub; } - static void sort(List l, [compareFn(a, b) = null]) { + static void sort/**/(List/**/ l, [int compareFn(/*=T*/a, /*=T*/b) = null]) { if (compareFn == null) { l.sort(); } else { @@ -232,7 +232,11 @@ class ListWrapper { bool isListLikeIterable(obj) => obj is Iterable; -bool areIterablesEqual(Iterable a, Iterable b, Function comparator) { +bool areIterablesEqual/**/( + Iterable/**/ a, + Iterable/**/ b, + bool comparator(/*=T*/a, /*=T*/b)) +{ var iterator1 = a.iterator; var iterator2 = b.iterator; @@ -241,11 +245,11 @@ bool areIterablesEqual(Iterable a, Iterable b, Function comparator) { var done2 = !iterator2.moveNext(); if (done1 && done2) return true; if (done1 || done2) return false; - if (!comparator(iterator2.current, iterator2.current)) return false; + if (!comparator(iterator1.current, iterator2.current)) return false; } } -void iterateListLike(iter, fn(item)) { +void iterateListLike/**/(Iterable/**/ iter, fn(/*=T*/item)) { assert(iter is Iterable); for (var item in iter) { fn(item); @@ -253,9 +257,9 @@ void iterateListLike(iter, fn(item)) { } class SetWrapper { - static Set createFromList(List l) => new Set.from(l); - static bool has(Set s, key) => s.contains(key); - static void delete(Set m, k) { + static Set/**/ createFromList/**/(List/**/ l) => new Set.from(l); + static bool has/**/(Set/**/ s, /*=T*/key) => s.contains(key); + static void delete/**/(Set/**/ m, /*=T*/k) { m.remove(k); } } diff --git a/modules/angular2/src/facade/lang.dart b/modules/angular2/src/facade/lang.dart index 13c8057997..6c8e63291f 100644 --- a/modules/angular2/src/facade/lang.dart +++ b/modules/angular2/src/facade/lang.dart @@ -20,16 +20,16 @@ class CONST { const IS_DART = true; -bool isPresent(obj) => obj != null; -bool isBlank(obj) => obj == null; -bool isString(obj) => obj is String; -bool isFunction(obj) => obj is Function; -bool isType(obj) => obj is Type; -bool isStringMap(obj) => obj is Map; -bool isArray(obj) => obj is List; -bool isPromise(obj) => obj is Future; -bool isNumber(obj) => obj is num; -bool isDate(obj) => obj is DateTime; +bool isPresent(Object obj) => obj != null; +bool isBlank(Object obj) => obj == null; +bool isString(Object obj) => obj is String; +bool isFunction(Object obj) => obj is Function; +bool isType(Object obj) => obj is Type; +bool isStringMap(Object obj) => obj is Map; +bool isArray(Object obj) => obj is List; +bool isPromise(Object obj) => obj is Future; +bool isNumber(Object obj) => obj is num; +bool isDate(Object obj) => obj is DateTime; String stringify(obj) { final exp = new RegExp(r"from Function '(\w+)'"); diff --git a/modules/angular2/src/facade/promise.dart b/modules/angular2/src/facade/promise.dart index 783ccddc0f..eda21d483a 100644 --- a/modules/angular2/src/facade/promise.dart +++ b/modules/angular2/src/facade/promise.dart @@ -4,22 +4,21 @@ import 'dart:async'; import 'dart:async' as async; class PromiseWrapper { - static Future resolve(obj) => new Future.value(obj); + static Future/**/ resolve/**/(dynamic /*=T*/ obj) => new Future.value(obj); - static Future reject(obj, stackTrace) => new Future.error(obj, - stackTrace != null ? stackTrace : obj is Error ? obj.stackTrace : null); + static Future/**/ reject/**/(dynamic /*=T*/ obj, Object stackTrace) => new Future.error(obj, + stackTrace != null ? stackTrace : obj is Error ? (obj as Error).stackTrace : null); - static Future all(List promises) { + static Future*/> all/**/(List promises) { return Future - .wait(promises.map((p) => p is Future ? p : new Future.value(p))); + .wait(promises.map((p) => p is Future ? p as Future/**/ : new Future/**/.value(p))); } - - static Future then(Future promise, success(value), [Function onError]) { + static Future/**/ then/**/(Future/**/ promise, dynamic /*=R*/ success(dynamic /*=T*/ value), [Function onError]) { if (success == null) return promise.catchError(onError); return promise.then(success, onError: onError); } - static Future wrap(Function fn) { + static Future/**/ wrap/**/(dynamic /*=T*/ fn()) { return new Future(fn); } @@ -37,16 +36,14 @@ class PromiseWrapper { return obj is Future; } - static PromiseCompleter completer() => - new PromiseCompleter(new Completer()); + static PromiseCompleter/**/ completer/**/() => + new PromiseCompleter(); } class PromiseCompleter { - final Completer c; + final Completer c = new Completer(); - PromiseCompleter(this.c); - - Future get promise => c.future; + Future get promise => c.future; void resolve(v) { c.complete(v); diff --git a/modules/angular2/src/facade/promise.ts b/modules/angular2/src/facade/promise.ts index 6e077fa5e0..b4fd77dfa5 100644 --- a/modules/angular2/src/facade/promise.ts +++ b/modules/angular2/src/facade/promise.ts @@ -1,8 +1,15 @@ -export interface PromiseCompleter { +export class PromiseCompleter { promise: Promise; resolve: (value?: R | PromiseLike) => void; reject: (error?: any, stackTrace?: string) => void; + + constructor() { + this.promise = new Promise((res, rej) => { + this.resolve = res; + this.reject = rej; + }); + } } export class PromiseWrapper { @@ -17,7 +24,7 @@ export class PromiseWrapper { return promise.catch(onError); } - static all(promises: any[]): Promise { + static all(promises: (T | Promise)[]): Promise { if (promises.length == 0) return Promise.resolve([]); return Promise.all(promises); } @@ -43,15 +50,5 @@ export class PromiseWrapper { static isPromise(obj: any): boolean { return obj instanceof Promise; } - static completer(): PromiseCompleter { - var resolve; - var reject; - - var p = new Promise(function(res, rej) { - resolve = res; - reject = rej; - }); - - return {promise: p, resolve: resolve, reject: reject}; - } + static completer(): PromiseCompleter { return new PromiseCompleter(); } } diff --git a/modules/angular2/src/platform/browser/generic_browser_adapter.ts b/modules/angular2/src/platform/browser/generic_browser_adapter.ts index a04ed83f9e..7c20c51796 100644 --- a/modules/angular2/src/platform/browser/generic_browser_adapter.ts +++ b/modules/angular2/src/platform/browser/generic_browser_adapter.ts @@ -31,7 +31,7 @@ export abstract class GenericBrowserDomAdapter extends DomAdapter { OTransition: 'oTransitionEnd otransitionend', transition: 'transitionend' }; - StringMapWrapper.forEach(transEndEventNames, (value, key) => { + StringMapWrapper.forEach(transEndEventNames, (value: string, key: string) => { if (isPresent(this.getStyle(element, key))) { this._transitionEnd = value; } diff --git a/modules/angular2/src/router/directives/router_outlet.ts b/modules/angular2/src/router/directives/router_outlet.ts index 457ceab264..7c066991ab 100644 --- a/modules/angular2/src/router/directives/router_outlet.ts +++ b/modules/angular2/src/router/directives/router_outlet.ts @@ -102,7 +102,7 @@ export class RouterOutlet implements OnDestroy { var next = _resolveToTrue; if (isPresent(this._componentRef) && isPresent(this._currentInstruction) && hasLifecycleHook(hookMod.routerOnDeactivate, this._currentInstruction.componentType)) { - next = PromiseWrapper.resolve( + next = >PromiseWrapper.resolve( (this._componentRef.instance) .routerOnDeactivate(nextInstruction, this._currentInstruction)); } @@ -127,7 +127,7 @@ export class RouterOutlet implements OnDestroy { return _resolveToTrue; } if (hasLifecycleHook(hookMod.routerCanDeactivate, this._currentInstruction.componentType)) { - return PromiseWrapper.resolve( + return >PromiseWrapper.resolve( (this._componentRef.instance) .routerCanDeactivate(nextInstruction, this._currentInstruction)); } @@ -158,7 +158,7 @@ export class RouterOutlet implements OnDestroy { (isPresent(nextInstruction.params) && isPresent(this._currentInstruction.params) && StringMapWrapper.equals(nextInstruction.params, this._currentInstruction.params)); } - return PromiseWrapper.resolve(result); + return >PromiseWrapper.resolve(result); } ngOnDestroy(): void { this._parentRouter.unregisterPrimaryOutlet(this); } diff --git a/modules/angular2/src/router/instruction.ts b/modules/angular2/src/router/instruction.ts index 02f4cd1a8c..b2ebf8531c 100644 --- a/modules/angular2/src/router/instruction.ts +++ b/modules/angular2/src/router/instruction.ts @@ -195,7 +195,7 @@ export abstract class Instruction { /** @internal */ _stringifyAux(): string { var routes = []; - StringMapWrapper.forEach(this.auxInstruction, (auxInstruction, _) => { + StringMapWrapper.forEach(this.auxInstruction, (auxInstruction: Instruction, _: string) => { routes.push(auxInstruction._stringifyPathMatrixAux()); }); if (routes.length > 0) { @@ -308,7 +308,7 @@ export class ComponentInstruction { */ constructor(public urlPath: string, public urlParams: string[], data: RouteData, public componentType, public terminal: boolean, public specificity: string, - public params: {[key: string]: any} = null) { + public params: {[key: string]: string} = null) { this.routeData = isPresent(data) ? data : BLANK_ROUTE_DATA; } } diff --git a/modules/angular2/src/router/interfaces.ts b/modules/angular2/src/router/interfaces.ts index d3b7464f11..a8e39993f3 100644 --- a/modules/angular2/src/router/interfaces.ts +++ b/modules/angular2/src/router/interfaces.ts @@ -5,7 +5,7 @@ import {global} from 'angular2/src/facade/lang'; // TODO(rado): find a better way to fix this, or remove if likely culprit // https://github.com/systemjs/systemjs/issues/487 gets closed. var __ignore_me = global; - +var __make_dart_analyzer_happy: Promise = null; /** * Defines route lifecycle method `routerOnActivate`, which is called by the router at the end of a @@ -27,7 +27,8 @@ var __ignore_me = global; */ export interface OnActivate { routerOnActivate(nextInstruction: ComponentInstruction, - prevInstruction: ComponentInstruction): any; + prevInstruction: ComponentInstruction): any | + Promise; } /** @@ -46,7 +47,8 @@ export interface OnActivate { * {@example router/ts/reuse/reuse_example.ts region='reuseCmp'} */ export interface OnReuse { - routerOnReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any; + routerOnReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any | + Promise; } /** @@ -66,7 +68,8 @@ export interface OnReuse { */ export interface OnDeactivate { routerOnDeactivate(nextInstruction: ComponentInstruction, - prevInstruction: ComponentInstruction): any; + prevInstruction: ComponentInstruction): any | + Promise; } /** @@ -90,7 +93,9 @@ export interface OnDeactivate { * {@example router/ts/reuse/reuse_example.ts region='reuseCmp'} */ export interface CanReuse { - routerCanReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any; + routerCanReuse(nextInstruction: ComponentInstruction, + prevInstruction: ComponentInstruction): boolean | + Promise; } /** @@ -114,5 +119,6 @@ export interface CanReuse { */ export interface CanDeactivate { routerCanDeactivate(nextInstruction: ComponentInstruction, - prevInstruction: ComponentInstruction): any; + prevInstruction: ComponentInstruction): boolean | + Promise; } diff --git a/modules/angular2/src/router/location/platform_location.ts b/modules/angular2/src/router/location/platform_location.ts index c6ed880024..7c41d2e692 100644 --- a/modules/angular2/src/router/location/platform_location.ts +++ b/modules/angular2/src/router/location/platform_location.ts @@ -27,9 +27,9 @@ export abstract class PlatformLocation { abstract onPopState(fn: UrlChangeListener): void; abstract onHashChange(fn: UrlChangeListener): void; - pathname: string; - search: string; - hash: string; + /* abstract */ get pathname(): string { return null; } + /* abstract */ get search(): string { return null; } + /* abstract */ get hash(): string { return null; } abstract replaceState(state: any, title: string, url: string): void; diff --git a/modules/angular2/src/router/route_config/route_config_impl.ts b/modules/angular2/src/router/route_config/route_config_impl.ts index f6f5a9fad6..22a115757f 100644 --- a/modules/angular2/src/router/route_config/route_config_impl.ts +++ b/modules/angular2/src/router/route_config/route_config_impl.ts @@ -4,6 +4,8 @@ import {RegexSerializer} from '../rules/route_paths/regex_route_path'; export {RouteDefinition} from '../route_definition'; +var __make_dart_analyzer_happy: Promise = null; + /** * The `RouteConfig` decorator defines routes for a given component. * @@ -136,7 +138,7 @@ export class AuxRoute extends AbstractRoute { */ @CONST() export class AsyncRoute extends AbstractRoute { - loader: Function; + loader: () => Promise; aux: string = null; constructor({name, useAsDefault, path, regex, serializer, data, loader}: RouteDefinition) { diff --git a/modules/angular2/src/router/route_config/route_config_normalizer.ts b/modules/angular2/src/router/route_config/route_config_normalizer.ts index edadae4bd0..ec50a38047 100644 --- a/modules/angular2/src/router/route_config/route_config_normalizer.ts +++ b/modules/angular2/src/router/route_config/route_config_normalizer.ts @@ -92,7 +92,8 @@ export function normalizeRouteConfig(config: RouteDefinition, } -function wrapLoaderToReconfigureRegistry(loader: Function, registry: RouteRegistry): Function { +function wrapLoaderToReconfigureRegistry(loader: Function, registry: RouteRegistry): () => + Promise { return () => { return loader().then((componentType) => { registry.configFromComponent(componentType); diff --git a/modules/angular2/src/router/route_definition.ts b/modules/angular2/src/router/route_definition.ts index e96a69975e..233b20230a 100644 --- a/modules/angular2/src/router/route_definition.ts +++ b/modules/angular2/src/router/route_definition.ts @@ -18,7 +18,7 @@ export interface RouteDefinition { regex?: string; serializer?: RegexSerializer; component?: Type | ComponentDefinition; - loader?: Function; + loader?: () => Promise; redirectTo?: any[]; as?: string; name?: string; @@ -34,6 +34,6 @@ export interface RouteDefinition { */ export interface ComponentDefinition { type: string; - loader?: Function; + loader?: () => Promise; component?: Type; } diff --git a/modules/angular2/src/router/route_registry.ts b/modules/angular2/src/router/route_registry.ts index fd765a4aa8..5805e1b211 100644 --- a/modules/angular2/src/router/route_registry.ts +++ b/modules/angular2/src/router/route_registry.ts @@ -37,8 +37,9 @@ import { import {normalizeRouteConfig, assertComponentExists} from './route_config/route_config_normalizer'; import {parser, Url, convertUrlParamsToArray, pathSegmentsToUrl} from './url_parser'; +import {GeneratedUrl} from './rules/route_paths/route_path'; -var _resolveToNull = PromiseWrapper.resolve(null); +var _resolveToNull = PromiseWrapper.resolve(null); // A LinkItemArray is an array, which describes a set of routes // The items in the array are found in groups: @@ -180,7 +181,7 @@ export class RouteRegistry { (candidate: Promise) => candidate.then((candidate: RouteMatch) => { if (candidate instanceof PathMatch) { - var auxParentInstructions = + var auxParentInstructions: Instruction[] = ancestorInstructions.length > 0 ? [ListWrapper.last(ancestorInstructions)] : []; var auxInstructions = this._auxRoutesToUnresolved(candidate.remainingAux, auxParentInstructions); @@ -191,7 +192,7 @@ export class RouteRegistry { return instruction; } - var newAncestorInstructions = ancestorInstructions.concat([instruction]); + var newAncestorInstructions: Instruction[] = ancestorInstructions.concat([instruction]); return this._recognize(candidate.remaining, newAncestorInstructions) .then((childInstruction) => { @@ -220,7 +221,7 @@ export class RouteRegistry { return PromiseWrapper.resolve(this.generateDefault(parentComponent)); } - return PromiseWrapper.all(matchPromises).then(mostSpecific); + return PromiseWrapper.all(matchPromises).then(mostSpecific); } private _auxRoutesToUnresolved(auxRoutes: Url[], @@ -400,7 +401,7 @@ export class RouteRegistry { // we'll figure out the rest of the route when we resolve the instruction and // perform a navigation if (isBlank(routeRecognizer.handler.componentType)) { - var generatedUrl = routeRecognizer.generateComponentPathValues(routeParams); + var generatedUrl: GeneratedUrl = routeRecognizer.generateComponentPathValues(routeParams); return new UnresolvedInstruction(() => { return routeRecognizer.handler.resolveComponentType().then((_) => { return this._generate(linkParams, ancestorInstructions, prevInstruction, _aux, @@ -416,7 +417,7 @@ export class RouteRegistry { // Next, recognize auxiliary instructions. // If we have an ancestor instruction, we preserve whatever aux routes are active from it. while (linkParamIndex < linkParams.length && isArray(linkParams[linkParamIndex])) { - let auxParentInstruction = [parentInstruction]; + let auxParentInstruction: Instruction[] = [parentInstruction]; let auxInstruction = this._generate(linkParams[linkParamIndex], auxParentInstruction, null, true, _originalLink); @@ -436,7 +437,7 @@ export class RouteRegistry { // TODO: throw that there are extra link params beyond the terminal component } } else { - let childAncestorComponents = ancestorInstructions.concat([instruction]); + let childAncestorComponents: Instruction[] = ancestorInstructions.concat([instruction]); let remainingLinkParams = linkParams.slice(linkParamIndex); childInstruction = this._generate(remainingLinkParams, childAncestorComponents, null, false, _originalLink); diff --git a/modules/angular2/src/router/router.ts b/modules/angular2/src/router/router.ts index 4a87b7cd5e..d98fd3fdbd 100644 --- a/modules/angular2/src/router/router.ts +++ b/modules/angular2/src/router/router.ts @@ -75,7 +75,7 @@ export class Router { * * You probably don't need to use this unless you're writing a reusable component. */ - registerPrimaryOutlet(outlet: RouterOutlet): Promise { + registerPrimaryOutlet(outlet: RouterOutlet): Promise { if (isPresent(outlet.name)) { throw new BaseException(`registerPrimaryOutlet expects to be called with an unnamed outlet.`); } @@ -109,7 +109,7 @@ export class Router { * * You probably don't need to use this unless you're writing a reusable component. */ - registerAuxOutlet(outlet: RouterOutlet): Promise { + registerAuxOutlet(outlet: RouterOutlet): Promise { var outletName = outlet.name; if (isBlank(outletName)) { throw new BaseException(`registerAuxOutlet expects to be called with an outlet with a name.`); @@ -230,7 +230,7 @@ export class Router { unsettledInstructions.push(this._settleInstruction(instruction.child)); } - StringMapWrapper.forEach(instruction.auxInstruction, (instruction, _) => { + StringMapWrapper.forEach(instruction.auxInstruction, (instruction: Instruction, _) => { unsettledInstructions.push(this._settleInstruction(instruction)); }); return PromiseWrapper.all(unsettledInstructions); @@ -311,7 +311,7 @@ export class Router { next = this._outlet.routerCanDeactivate(componentInstruction); } // TODO: aux route lifecycle hooks - return next.then((result) => { + return next.then((result): boolean | Promise => { if (result == false) { return false; } @@ -346,7 +346,7 @@ export class Router { } } - var promises = []; + var promises: Promise[] = []; this._auxRouters.forEach((router, name) => { if (isPresent(instruction.auxInstruction[name])) { promises.push(router.commit(instruction.auxInstruction[name])); @@ -405,7 +405,7 @@ export class Router { } private _getAncestorInstructions(): Instruction[] { - var ancestorInstructions = [this.currentInstruction]; + var ancestorInstructions: Instruction[] = [this.currentInstruction]; var ancestorRouter: Router = this; while (isPresent(ancestorRouter = ancestorRouter.parent)) { ancestorInstructions.unshift(ancestorRouter.currentInstruction); @@ -534,7 +534,7 @@ function canActivateOne(nextInstruction: Instruction, next = canActivateOne(nextInstruction.child, isPresent(prevInstruction) ? prevInstruction.child : null); } - return next.then((result) => { + return next.then((result: boolean): boolean => { if (result == false) { return false; } diff --git a/modules/angular2/src/router/rules/route_handlers/async_route_handler.ts b/modules/angular2/src/router/rules/route_handlers/async_route_handler.ts index 5c425afa30..d09518580b 100644 --- a/modules/angular2/src/router/rules/route_handlers/async_route_handler.ts +++ b/modules/angular2/src/router/rules/route_handlers/async_route_handler.ts @@ -6,15 +6,15 @@ import {RouteData, BLANK_ROUTE_DATA} from '../../instruction'; export class AsyncRouteHandler implements RouteHandler { /** @internal */ - _resolvedComponent: Promise = null; + _resolvedComponent: Promise = null; componentType: Type; public data: RouteData; - constructor(private _loader: Function, data: {[key: string]: any} = null) { + constructor(private _loader: () => Promise, data: {[key: string]: any} = null) { this.data = isPresent(data) ? new RouteData(data) : BLANK_ROUTE_DATA; } - resolveComponentType(): Promise { + resolveComponentType(): Promise { if (isPresent(this._resolvedComponent)) { return this._resolvedComponent; } diff --git a/modules/angular2/src/router/url_parser.ts b/modules/angular2/src/router/url_parser.ts index a208222ffc..1f0afe62de 100644 --- a/modules/angular2/src/router/url_parser.ts +++ b/modules/angular2/src/router/url_parser.ts @@ -113,7 +113,7 @@ export class UrlParser { var path = matchUrlSegment(this._remaining); this.capture(path); - var aux = []; + var aux: Url[] = []; if (this.peekStartsWith('(')) { aux = this.parseAuxiliaryRoutes(); } @@ -126,7 +126,7 @@ export class UrlParser { this.capture('/'); child = this.parseSegment(); } - var queryParams = null; + var queryParams: {[key: string]: any} = null; if (this.peekStartsWith('?')) { queryParams = this.parseQueryParams(); } @@ -144,15 +144,15 @@ export class UrlParser { var path = matchUrlSegment(this._remaining); this.capture(path); - var matrixParams = null; + var matrixParams: {[key: string]: any} = null; if (this.peekStartsWith(';')) { matrixParams = this.parseMatrixParams(); } - var aux = []; + var aux: Url[] = []; if (this.peekStartsWith('(')) { aux = this.parseAuxiliaryRoutes(); } - var child = null; + var child: Url = null; if (this.peekStartsWith('/') && !this.peekStartsWith('//')) { this.capture('/'); child = this.parseSegment(); @@ -161,7 +161,7 @@ export class UrlParser { } parseQueryParams(): {[key: string]: any} { - var params = {}; + var params: {[key: string]: any} = {}; this.capture('?'); this.parseParam(params); while (this._remaining.length > 0 && this.peekStartsWith('&')) { @@ -172,7 +172,7 @@ export class UrlParser { } parseMatrixParams(): {[key: string]: any} { - var params = {}; + var params: {[key: string]: any} = {}; while (this._remaining.length > 0 && this.peekStartsWith(';')) { this.capture(';'); this.parseParam(params); @@ -200,7 +200,7 @@ export class UrlParser { } parseAuxiliaryRoutes(): Url[] { - var routes = []; + var routes: Url[] = []; this.capture('('); while (!this.peekStartsWith(')') && this._remaining.length > 0) { @@ -215,4 +215,4 @@ export class UrlParser { } } -export var parser = new UrlParser(); \ No newline at end of file +export var parser = new UrlParser(); diff --git a/modules/angular2/src/testing/e2e_util.ts b/modules/angular2/src/testing/e2e_util.ts index 027c808838..325ecebcdf 100644 --- a/modules/angular2/src/testing/e2e_util.ts +++ b/modules/angular2/src/testing/e2e_util.ts @@ -18,6 +18,6 @@ export function verifyNoBrowserErrors() { } return logEntry.level.value > webdriver.logging.Level.WARNING.value; }); - expect(filteredLog.length).toEqual(0); + expect(filteredLog).toEqual([]); }); } diff --git a/modules/angular2/src/testing/test_component_builder.ts b/modules/angular2/src/testing/test_component_builder.ts index 1f68e57c3a..8b72401f0f 100644 --- a/modules/angular2/src/testing/test_component_builder.ts +++ b/modules/angular2/src/testing/test_component_builder.ts @@ -254,8 +254,9 @@ export class TestComponentBuilder { DOM.appendChild(doc.body, rootEl); - return this._injector.get(DynamicComponentLoader) - .loadAsRoot(rootComponentType, `#${rootElId}`, this._injector) - .then((componentRef) => { return new ComponentFixture_(componentRef); }); + var promise: Promise = + this._injector.get(DynamicComponentLoader) + .loadAsRoot(rootComponentType, `#${rootElId}`, this._injector); + return promise.then((componentRef) => { return new ComponentFixture_(componentRef); }); } } diff --git a/modules/angular2/test/common/forms/validators_spec.ts b/modules/angular2/test/common/forms/validators_spec.ts index 54f6728a7a..5b049cdabc 100644 --- a/modules/angular2/test/common/forms/validators_spec.ts +++ b/modules/angular2/test/common/forms/validators_spec.ts @@ -140,7 +140,7 @@ export function main() { ]); var value = null; - c(new Control("invalid")).then(v => value = v); + (>c(new Control("invalid"))).then(v => value = v); tick(1); @@ -151,7 +151,7 @@ export function main() { var c = Validators.composeAsync([asyncValidator("expected", {"one": true})]); var value = null; - c(new Control("expected")).then(v => value = v); + (>c(new Control("expected"))).then(v => value = v); tick(1); @@ -162,7 +162,7 @@ export function main() { var c = Validators.composeAsync([asyncValidator("expected", {"one": true}), null]); var value = null; - c(new Control("invalid")).then(v => value = v); + (>c(new Control("invalid"))).then(v => value = v); tick(1); diff --git a/modules/angular2/test/common/pipes/async_pipe_spec.ts b/modules/angular2/test/common/pipes/async_pipe_spec.ts index d962e95a17..25ebfbe491 100644 --- a/modules/angular2/test/common/pipes/async_pipe_spec.ts +++ b/modules/angular2/test/common/pipes/async_pipe_spec.ts @@ -23,6 +23,7 @@ import { TimerWrapper } from 'angular2/src/facade/async'; import {DOM} from 'angular2/src/platform/dom/dom_adapter'; +import {PromiseCompleter} from 'angular2/src/facade/promise'; export function main() { describe("AsyncPipe", () => { @@ -116,16 +117,16 @@ export function main() { describe("Promise", () => { var message = new Object(); - var pipe; - var completer; - var ref; + var pipe: AsyncPipe; + var completer: PromiseCompleter; + var ref: SpyChangeDetectorRef; // adds longer timers for passing tests in IE var timer = (!isBlank(DOM) && browserDetection.isIE) ? 50 : 0; beforeEach(() => { completer = PromiseWrapper.completer(); ref = new SpyChangeDetectorRef(); - pipe = new AsyncPipe(ref); + pipe = new AsyncPipe(ref); }); describe("transform", () => { diff --git a/modules/angular2/test/compiler/template_compiler_spec.ts b/modules/angular2/test/compiler/template_compiler_spec.ts index 95ceda9f91..259b2c1a1c 100644 --- a/modules/angular2/test/compiler/template_compiler_spec.ts +++ b/modules/angular2/test/compiler/template_compiler_spec.ts @@ -76,14 +76,15 @@ export function main() { describe('compile templates', () => { - function runTests(compile) { + function runTests(compile: (components: Type[]) => Promise) { it('should throw for non components', inject([AsyncTestCompleter], (async) => { - PromiseWrapper.catchError(PromiseWrapper.wrap(() => compile([NonComponent])), (error) => { - expect(error.message) - .toEqual( - `Could not compile '${stringify(NonComponent)}' because it is not a component.`); - async.done(); - }); + PromiseWrapper.catchError( + PromiseWrapper.wrap(() => compile([NonComponent])), (error): any => { + expect(error.message) + .toEqual( + `Could not compile '${stringify(NonComponent)}' because it is not a component.`); + async.done(); + }); })); it('should compile host components', inject([AsyncTestCompleter], (async) => { diff --git a/modules/angular2/test/compiler/url_resolver_spec.ts b/modules/angular2/test/compiler/url_resolver_spec.ts index 21f4e13ac0..420ef7ae44 100644 --- a/modules/angular2/test/compiler/url_resolver_spec.ts +++ b/modules/angular2/test/compiler/url_resolver_spec.ts @@ -99,14 +99,14 @@ export function main() { }); it('should contain a default value of "/packages" when nothing is provided for DART', - inject([UrlResolver], (resolver) => { + inject([UrlResolver], (resolver: UrlResolver) => { if (IS_DART) { expect(resolver.resolve(null, 'package:file')).toEqual('/packages/file'); } })); it('should contain a default value of "/" when nothing is provided for TS/ESM', - inject([UrlResolver], (resolver) => { + inject([UrlResolver], (resolver: UrlResolver) => { if (!IS_DART) { expect(resolver.resolve(null, 'package:file')).toEqual('/file'); } diff --git a/modules/angular2/test/core/application_ref_spec.ts b/modules/angular2/test/core/application_ref_spec.ts index 0d24f350c9..e11463fa83 100644 --- a/modules/angular2/test/core/application_ref_spec.ts +++ b/modules/angular2/test/core/application_ref_spec.ts @@ -65,8 +65,8 @@ export function main() { }); })); - function mockAsyncAppInitializer(completer, providers: Array = null, - injector?: Injector) { + function mockAsyncAppInitializer(completer: PromiseCompleter, + providers: Array = null, injector?: Injector) { return () => { if (providers != null) { expectProviders(injector, providers); @@ -76,23 +76,11 @@ export function main() { }; } - function createSpyPromiseCompleter(): SpyObject { - let completer = PromiseWrapper.completer(); - let completerSpy = new SpyObject(); - // Note that in TypeScript we need to provide a value for the promise attribute - // whereas in dart we need to override the promise getter - completerSpy.promise = completer.promise; - completerSpy.spy("get:promise").andReturn(completer.promise); - completerSpy.spy("resolve").andCallFake(completer.resolve); - completerSpy.spy("reject").andCallFake(completer.reject); - return completerSpy; - } - it("should wait for asyncronous app initializers", inject([AsyncTestCompleter, Injector], (async, injector) => { let ref = new PlatformRef_(injector, null); - let completer = createSpyPromiseCompleter(); + let completer: PromiseCompleter = PromiseWrapper.completer(); let SYNC_PROVIDERS = [ new Provider(Bar, {useValue: new Bar()}), new Provider(APP_INITIALIZER, @@ -102,8 +90,7 @@ export function main() { .then((appRef) => { expectProviders(appRef.injector, SYNC_PROVIDERS.slice(0, SYNC_PROVIDERS.length - 1)); - expect(completer.spy("resolve")).toHaveBeenCalled(); - async.done(); + completer.promise.then((_) => async.done()); }); })); @@ -111,13 +98,13 @@ export function main() { inject([AsyncTestCompleter, Injector], (async, injector) => { let ref = new PlatformRef_(injector, null); let ASYNC_PROVIDERS = [new Provider(Foo, {useValue: new Foo()})]; - let completer = createSpyPromiseCompleter(); + let completer: PromiseCompleter = PromiseWrapper.completer(); let SYNC_PROVIDERS = [ new Provider(Bar, {useValue: new Bar()}), new Provider(APP_INITIALIZER, { useFactory: (injector) => mockAsyncAppInitializer( - completer, ASYNC_PROVIDERS, injector), + completer, ASYNC_PROVIDERS, injector), multi: true, deps: [Injector] }) @@ -126,8 +113,7 @@ export function main() { .then((appRef) => { expectProviders(appRef.injector, SYNC_PROVIDERS.slice(0, SYNC_PROVIDERS.length - 1)); - expect(completer.spy("resolve")).toHaveBeenCalled(); - async.done(); + completer.promise.then((_) => async.done()); }); })); }); diff --git a/modules/angular2/test/core/linker/compiler_spec.ts b/modules/angular2/test/core/linker/compiler_spec.ts index 480c0bd349..0ba3e5a34c 100644 --- a/modules/angular2/test/core/linker/compiler_spec.ts +++ b/modules/angular2/test/core/linker/compiler_spec.ts @@ -18,6 +18,7 @@ import {Compiler} from 'angular2/src/core/linker/compiler'; import {reflector, ReflectionInfo} from 'angular2/src/core/reflection/reflection'; import {Compiler_} from "angular2/src/core/linker/compiler"; import {HostViewFactory} from 'angular2/src/core/linker/view'; +import {HostViewFactoryRef_} from 'angular2/src/core/linker/view_ref'; export function main() { describe('Compiler', () => { @@ -31,11 +32,12 @@ export function main() { })); it('should read the template from an annotation', - inject([AsyncTestCompleter, Compiler], (async, compiler) => { + inject([AsyncTestCompleter, Compiler], (async, compiler: Compiler) => { compiler.compileInHost(SomeComponent) - .then((hostViewFactoryRef) => { + .then((hostViewFactoryRef: HostViewFactoryRef_) => { expect(hostViewFactoryRef.internalHostViewFactory).toBe(someHostViewFactory); async.done(); + return null; }); })); diff --git a/modules/angular2/test/core/linker/directive_resolver_spec.ts b/modules/angular2/test/core/linker/directive_resolver_spec.ts index 2acaa35375..84a8c80cf1 100644 --- a/modules/angular2/test/core/linker/directive_resolver_spec.ts +++ b/modules/angular2/test/core/linker/directive_resolver_spec.ts @@ -113,7 +113,7 @@ class SomeDirectiveWithoutMetadata {} export function main() { describe("DirectiveResolver", () => { - var resolver; + var resolver: DirectiveResolver; beforeEach(() => { resolver = new DirectiveResolver(); }); diff --git a/modules/angular2/test/core/linker/dynamic_component_loader_spec.ts b/modules/angular2/test/core/linker/dynamic_component_loader_spec.ts index 2ff6c3a684..d5ca412681 100644 --- a/modules/angular2/test/core/linker/dynamic_component_loader_spec.ts +++ b/modules/angular2/test/core/linker/dynamic_component_loader_spec.ts @@ -34,7 +34,7 @@ export function main() { describe("loading into a location", () => { it('should work', inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], - (loader, tcb: TestComponentBuilder, async) => { + (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { tcb.overrideView( MyComp, new ViewMetadata( @@ -52,7 +52,7 @@ export function main() { it('should return a disposable component ref', inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], - (loader, tcb: TestComponentBuilder, async) => { + (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { tcb.overrideView( MyComp, new ViewMetadata( @@ -72,7 +72,7 @@ export function main() { it('should allow to dispose even if the location has been removed', inject( [DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], - (loader, tcb: TestComponentBuilder, async) => { + (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new ViewMetadata({ template: '', directives: [NgIf, ChildComp] @@ -109,7 +109,7 @@ export function main() { it('should update host properties', inject( [DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], - (loader, tcb: TestComponentBuilder, async) => { + (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { tcb.overrideView( MyComp, new ViewMetadata( {template: '', directives: [Location]})) @@ -131,7 +131,7 @@ export function main() { it('should leave the view tree in a consistent state if hydration fails', inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], - (loader, tcb: TestComponentBuilder, async) => { + (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new ViewMetadata({ template: '
', directives: [Location] @@ -147,13 +147,14 @@ export function main() { expect(error.message).toContain("ThrownInConstructor"); expect(() => tc.detectChanges()).not.toThrow(); async.done(); + return null; }); }); })); it('should throw if the variable does not exist', inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], - (loader, tcb: TestComponentBuilder, async) => { + (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { tcb.overrideView( MyComp, new ViewMetadata( @@ -169,7 +170,7 @@ export function main() { it('should allow to pass projectable nodes', inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], - (loader, tcb: TestComponentBuilder, async) => { + (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new ViewMetadata({template: '
', directives: []})) .createAsync(MyComp) @@ -187,7 +188,7 @@ export function main() { it('should throw if not enough projectable nodes are passed in', inject( [DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], - (loader, tcb: TestComponentBuilder, async) => { + (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new ViewMetadata({template: '
', directives: []})) .createAsync(MyComp) @@ -199,6 +200,7 @@ export function main() { expect(e.message).toContain( `The component ${stringify(DynamicallyLoadedWithNgContent)} has 1 elements, but only 0 slots were provided`); async.done(); + return null; }); }); })); @@ -208,7 +210,7 @@ export function main() { describe("loading next to a location", () => { it('should work', inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], - (loader, tcb: TestComponentBuilder, async) => { + (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new ViewMetadata({ template: '
', directives: [Location] @@ -228,7 +230,7 @@ export function main() { it('should return a disposable component ref', inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], - (loader, tcb: TestComponentBuilder, async) => { + (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new ViewMetadata({ template: '
', directives: [Location] @@ -262,7 +264,7 @@ export function main() { it('should update host properties', inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], - (loader, tcb: TestComponentBuilder, async) => { + (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new ViewMetadata({ template: '
', directives: [Location] @@ -288,7 +290,7 @@ export function main() { it('should allow to pass projectable nodes', inject([DynamicComponentLoader, TestComponentBuilder, AsyncTestCompleter], - (loader, tcb: TestComponentBuilder, async) => { + (loader: DynamicComponentLoader, tcb: TestComponentBuilder, async) => { tcb.overrideView(MyComp, new ViewMetadata({template: '', directives: [Location]})) .createAsync(MyComp) .then((tc) => { @@ -309,7 +311,8 @@ export function main() { describe('loadAsRoot', () => { it('should allow to create, update and destroy components', inject([AsyncTestCompleter, DynamicComponentLoader, DOCUMENT, Injector], - (async, loader, doc, injector) => { + (async: AsyncTestCompleter, loader: DynamicComponentLoader, doc, + injector: Injector) => { var rootEl = createRootElement(doc, 'child-cmp'); DOM.appendChild(doc.body, rootEl); loader.loadAsRoot(ChildComp, null, injector) @@ -338,7 +341,8 @@ export function main() { it('should allow to pass projectable nodes', inject([AsyncTestCompleter, DynamicComponentLoader, DOCUMENT, Injector], - (async, loader, doc, injector) => { + (async: AsyncTestCompleter, loader: DynamicComponentLoader, doc, + injector: Injector) => { var rootEl = createRootElement(doc, 'dummy'); DOM.appendChild(doc.body, rootEl); loader.loadAsRoot(DynamicallyLoadedWithNgContent, null, injector, null, diff --git a/modules/angular2/test/core/linker/integration_spec.ts b/modules/angular2/test/core/linker/integration_spec.ts index 8a0a3b5962..b85d70faf6 100644 --- a/modules/angular2/test/core/linker/integration_spec.ts +++ b/modules/angular2/test/core/linker/integration_spec.ts @@ -818,7 +818,8 @@ function declareTests() { tcb.createAsync(MyComp).then(root => { fixture = root; }); tick(); - var cmp = fixture.debugElement.children[0].getLocal('cmp'); + var cmp: PushCmpWithAsyncPipe = + fixture.debugElement.children[0].getLocal('cmp'); fixture.detectChanges(); expect(cmp.numberOfChecks).toEqual(1); @@ -1155,7 +1156,7 @@ function declareTests() { .createAsync(MyComp) .then((fixture) => { var tc = fixture.debugElement.children[0].children[0]; - var dynamicVp = tc.inject(DynamicViewport); + var dynamicVp: DynamicViewport = tc.inject(DynamicViewport); dynamicVp.done.then((_) => { fixture.detectChanges(); expect(fixture.debugElement.children[0].children[1].nativeElement) @@ -1549,7 +1550,7 @@ function declareTests() { it('should support moving embedded views around', inject([TestComponentBuilder, AsyncTestCompleter, ANCHOR_ELEMENT], - (tcb, async, anchorElement) => { + (tcb: TestComponentBuilder, async, anchorElement) => { tcb.overrideView(MyComp, new ViewMetadata({ template: '
hello
', directives: [SomeImperativeViewport] @@ -1950,7 +1951,7 @@ class SimpleImperativeViewComponent { @Directive({selector: 'dynamic-vp'}) @Injectable() class DynamicViewport { - done; + done: Promise; constructor(vc: ViewContainerRef, compiler: Compiler) { var myService = new MyService(); myService.greeting = 'dynamic greet'; diff --git a/modules/angular2/test/core/linker/projection_integration_spec.ts b/modules/angular2/test/core/linker/projection_integration_spec.ts index abd45c0d29..f592f57912 100644 --- a/modules/angular2/test/core/linker/projection_integration_spec.ts +++ b/modules/angular2/test/core/linker/projection_integration_spec.ts @@ -286,7 +286,7 @@ export function main() { // important as we are removing the ng-content element during compilation, // which could skrew up text node indices. it('should support text nodes after content tags', - inject([TestComponentBuilder, AsyncTestCompleter], (tcb, async) => { + inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView( MainComp, @@ -307,7 +307,7 @@ export function main() { // important as we are moving style tags around during compilation, // which could skrew up text node indices. it('should support text nodes after style tags', - inject([TestComponentBuilder, AsyncTestCompleter], (tcb, async) => { + inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { tcb.overrideView( MainComp, diff --git a/modules/angular2/test/core/linker/view_resolver_spec.ts b/modules/angular2/test/core/linker/view_resolver_spec.ts index 06028796cb..77f29be301 100644 --- a/modules/angular2/test/core/linker/view_resolver_spec.ts +++ b/modules/angular2/test/core/linker/view_resolver_spec.ts @@ -43,7 +43,7 @@ class SimpleClass {} export function main() { describe("ViewResolver", () => { - var resolver; + var resolver: ViewResolver; beforeEach(() => { resolver = new ViewResolver(); }); diff --git a/modules/angular2/test/core/zone/ng_zone_DEPRECATED_spec.ts b/modules/angular2/test/core/zone/ng_zone_DEPRECATED_spec.ts index 5d3d6e8685..358b34aa0a 100644 --- a/modules/angular2/test/core/zone/ng_zone_DEPRECATED_spec.ts +++ b/modules/angular2/test/core/zone/ng_zone_DEPRECATED_spec.ts @@ -566,7 +566,7 @@ function commonTests() { it('should call onTurnStart and onTurnDone for promises created outside of run body', inject([AsyncTestCompleter], (async) => { - var promise; + var promise: Promise; macroTask(() => { _zone.runOutsideAngular(() => { diff --git a/modules/angular2/test/core/zone/ng_zone_spec.ts b/modules/angular2/test/core/zone/ng_zone_spec.ts index 13f7b21b64..1c011cc37d 100644 --- a/modules/angular2/test/core/zone/ng_zone_spec.ts +++ b/modules/angular2/test/core/zone/ng_zone_spec.ts @@ -674,7 +674,7 @@ function commonTests() { logOnTurnStart(); logOnTurnDone(); - var promise; + var promise: Promise; macroTask(() => { _zone.runOutsideAngular(() => { diff --git a/modules/angular2/test/mock/view_resolver_mock_spec.ts b/modules/angular2/test/mock/view_resolver_mock_spec.ts index f9f09cf869..5ad9377b78 100644 --- a/modules/angular2/test/mock/view_resolver_mock_spec.ts +++ b/modules/angular2/test/mock/view_resolver_mock_spec.ts @@ -18,7 +18,7 @@ import {isBlank} from 'angular2/src/facade/lang'; export function main() { describe('MockViewResolver', () => { - var viewResolver; + var viewResolver: MockViewResolver; beforeEach(() => { viewResolver = new MockViewResolver(); }); diff --git a/modules/angular2/test/platform/browser/bootstrap_spec.ts b/modules/angular2/test/platform/browser/bootstrap_spec.ts index 8b4fa34455..1cdf67f222 100644 --- a/modules/angular2/test/platform/browser/bootstrap_spec.ts +++ b/modules/angular2/test/platform/browser/bootstrap_spec.ts @@ -25,7 +25,7 @@ import {provide, Inject, Injector, PLATFORM_INITIALIZER, APP_INITIALIZER} from ' import {disposePlatform} from 'angular2/src/core/application_ref'; import {ExceptionHandler} from 'angular2/src/facade/exceptions'; import {Testability, TestabilityRegistry} from 'angular2/src/core/testability/testability'; -import {ComponentRef_} from "angular2/src/core/linker/dynamic_component_loader"; +import {ComponentRef_, ComponentRef} from "angular2/src/core/linker/dynamic_component_loader"; @Component({selector: 'hello-app'}) @View({template: '{{greeting}} world!'}) @@ -243,11 +243,11 @@ export function main() { it('should register each application with the testability registry', inject([AsyncTestCompleter], (async) => { - var refPromise1 = bootstrap(HelloRootCmp, testProviders); - var refPromise2 = bootstrap(HelloRootCmp2, testProviders); + var refPromise1: Promise = bootstrap(HelloRootCmp, testProviders); + var refPromise2: Promise = bootstrap(HelloRootCmp2, testProviders); PromiseWrapper.all([refPromise1, refPromise2]) - .then((refs: ApplicationRef[]) => { + .then((refs: ComponentRef[]) => { var registry = refs[0].injector.get(TestabilityRegistry); var testabilities = [refs[0].injector.get(Testability), refs[1].injector.get(Testability)]; diff --git a/modules/angular2/test/router/integration/impl/sync_route_spec_impl.ts b/modules/angular2/test/router/integration/impl/sync_route_spec_impl.ts index 71fbfa5a43..0a1f7af132 100644 --- a/modules/angular2/test/router/integration/impl/sync_route_spec_impl.ts +++ b/modules/angular2/test/router/integration/impl/sync_route_spec_impl.ts @@ -430,8 +430,8 @@ function syncRoutesWithSyncChildrenWithDefaultRoutesWithoutParams() { } function syncRoutesWithDynamicComponents() { - var fixture; - var tcb; + var fixture: ComponentFixture; + var tcb: TestComponentBuilder; var rtr: Router; beforeEachProviders(() => TEST_ROUTER_PROVIDERS); diff --git a/modules/angular2/test/router/integration/lifecycle_hook_spec.ts b/modules/angular2/test/router/integration/lifecycle_hook_spec.ts index 94a4ee247b..5bf40d7f10 100644 --- a/modules/angular2/test/router/integration/lifecycle_hook_spec.ts +++ b/modules/angular2/test/router/integration/lifecycle_hook_spec.ts @@ -56,17 +56,18 @@ export function main() { var tcb: TestComponentBuilder; var fixture: ComponentFixture; - var rtr; + var rtr: Router; beforeEachProviders(() => TEST_ROUTER_PROVIDERS); - beforeEach(inject([TestComponentBuilder, Router], (tcBuilder, router) => { - tcb = tcBuilder; - rtr = router; - cmpInstanceCount = 0; - log = []; - eventBus = new EventEmitter(); - })); + beforeEach(inject([TestComponentBuilder, Router], + (tcBuilder: TestComponentBuilder, router: Router) => { + tcb = tcBuilder; + rtr = router; + cmpInstanceCount = 0; + log = []; + eventBus = new EventEmitter(); + })); it('should call the routerOnActivate hook', inject([AsyncTestCompleter], (async) => { compile(tcb) diff --git a/modules/angular2/test/router/integration/router_link_spec.ts b/modules/angular2/test/router/integration/router_link_spec.ts index 306709537e..3427624288 100644 --- a/modules/angular2/test/router/integration/router_link_spec.ts +++ b/modules/angular2/test/router/integration/router_link_spec.ts @@ -49,7 +49,8 @@ export function main() { describe('routerLink directive', function() { var tcb: TestComponentBuilder; var fixture: ComponentFixture; - var router, location; + var router: Router; + var location: Location; beforeEachProviders(() => [ RouteRegistry, @@ -60,11 +61,12 @@ export function main() { provide(TEMPLATE_TRANSFORMS, {useClass: RouterLinkTransform, multi: true}) ]); - beforeEach(inject([TestComponentBuilder, Router, Location], (tcBuilder, rtr, loc) => { - tcb = tcBuilder; - router = rtr; - location = loc; - })); + beforeEach(inject([TestComponentBuilder, Router, Location], + (tcBuilder, rtr: Router, loc: Location) => { + tcb = tcBuilder; + router = rtr; + location = loc; + })); function compile(template: string = "") { return tcb.overrideView(MyComp, new View({ @@ -77,7 +79,7 @@ export function main() { it('should generate absolute hrefs that include the base href', inject([AsyncTestCompleter], (async) => { - location.setBaseHref('/my/base'); + (location).setBaseHref('/my/base'); compile('') .then((_) => router.config( [new Route({path: '/user', component: UserCmp, name: 'User'})])) @@ -345,7 +347,7 @@ export function main() { // router navigation is async. router.subscribe((_) => { - expect(location.urlChanges).toEqual(['/user']); + expect((location).urlChanges).toEqual(['/user']); async.done(); }); }); @@ -353,7 +355,7 @@ export function main() { it('should navigate to link hrefs in presence of base href', inject([AsyncTestCompleter], (async) => { - location.setBaseHref('/base'); + (location).setBaseHref('/base'); compile('') .then((_) => router.config( [new Route({path: '/user', component: UserCmp, name: 'User'})])) @@ -367,7 +369,7 @@ export function main() { // router navigation is async. router.subscribe((_) => { - expect(location.urlChanges).toEqual(['/base/user']); + expect((location).urlChanges).toEqual(['/base/user']); async.done(); }); }); diff --git a/modules/angular2/test/router/route_registry_spec.ts b/modules/angular2/test/router/route_registry_spec.ts index d0f1808f6e..df9b9f2384 100644 --- a/modules/angular2/test/router/route_registry_spec.ts +++ b/modules/angular2/test/router/route_registry_spec.ts @@ -25,7 +25,7 @@ import { export function main() { describe('RouteRegistry', () => { - var registry; + var registry: RouteRegistry; beforeEach(() => { registry = new RouteRegistry(RootHostCmp); }); diff --git a/modules/angular2/test/router/router_spec.ts b/modules/angular2/test/router/router_spec.ts index 5027eefbca..27ce712d27 100644 --- a/modules/angular2/test/router/router_spec.ts +++ b/modules/angular2/test/router/router_spec.ts @@ -30,10 +30,12 @@ import { import {DirectiveResolver} from 'angular2/src/core/linker/directive_resolver'; import {provide} from 'angular2/core'; +import {RouterOutlet} from 'angular2/src/router/directives/router_outlet'; export function main() { describe('Router', () => { - var router, location; + var router: Router; + var location: Location; beforeEachProviders(() => [ RouteRegistry, @@ -44,7 +46,7 @@ export function main() { ]); - beforeEach(inject([Router, Location], (rtr, loc) => { + beforeEach(inject([Router, Location], (rtr: Router, loc: Location) => { router = rtr; location = loc; })); @@ -56,8 +58,8 @@ export function main() { router.config([new Route({path: '/', component: DummyComponent})]) .then((_) => router.registerPrimaryOutlet(outlet)) .then((_) => { - expect(outlet.spy('activate')).toHaveBeenCalled(); - expect(location.urlChanges).toEqual([]); + expect((outlet).spy('activate')).toHaveBeenCalled(); + expect((location).urlChanges).toEqual([]); async.done(); }); })); @@ -70,8 +72,8 @@ export function main() { .then((_) => router.config([new Route({path: '/a', component: DummyComponent})])) .then((_) => router.navigateByUrl('/a')) .then((_) => { - expect(outlet.spy('activate')).toHaveBeenCalled(); - expect(location.urlChanges).toEqual(['/a']); + expect((outlet).spy('activate')).toHaveBeenCalled(); + expect((location).urlChanges).toEqual(['/a']); async.done(); }); })); @@ -85,8 +87,8 @@ export function main() { [new Route({path: '/a', component: DummyComponent, name: 'A'})])) .then((_) => router.navigate(['/A'])) .then((_) => { - expect(outlet.spy('activate')).toHaveBeenCalled(); - expect(location.urlChanges).toEqual(['/a']); + expect((outlet).spy('activate')).toHaveBeenCalled(); + expect((location).urlChanges).toEqual(['/a']); async.done(); }); })); @@ -99,8 +101,8 @@ export function main() { .then((_) => router.config([new Route({path: '/b', component: DummyComponent})])) .then((_) => router.navigateByUrl('/b', true)) .then((_) => { - expect(outlet.spy('activate')).toHaveBeenCalled(); - expect(location.urlChanges).toEqual([]); + expect((outlet).spy('activate')).toHaveBeenCalled(); + expect((location).urlChanges).toEqual([]); async.done(); }); })); @@ -119,11 +121,11 @@ export function main() { ])) .then((_) => { router.subscribe((_) => { - expect(location.urlChanges).toEqual(['hash: a', 'replace: /b']); + expect((location).urlChanges).toEqual(['hash: a', 'replace: /b']); async.done(); }); - location.simulateHashChange('a'); + (location).simulateHashChange('a'); }); })); @@ -135,11 +137,11 @@ export function main() { .then((_) => router.config([new Route({path: '/a', component: DummyComponent})])) .then((_) => { router.subscribe((_) => { - expect(location.urlChanges).toEqual(['hash: a']); + expect((location).urlChanges).toEqual(['hash: a']); async.done(); }); - location.simulateHashChange('a'); + (location).simulateHashChange('a'); }); })); @@ -149,11 +151,11 @@ export function main() { router.registerPrimaryOutlet(outlet) .then((_) => router.navigateByUrl('/a')) .then((_) => { - expect(outlet.spy('activate')).not.toHaveBeenCalled(); + expect((outlet).spy('activate')).not.toHaveBeenCalled(); return router.config([new Route({path: '/a', component: DummyComponent})]); }) .then((_) => { - expect(outlet.spy('activate')).toHaveBeenCalled(); + expect((outlet).spy('activate')).toHaveBeenCalled(); async.done(); }); })); @@ -193,7 +195,7 @@ export function main() { var instruction = router.generate(['/FirstCmp']); router.navigateByInstruction(instruction) .then((_) => { - expect(outlet.spy('activate')).toHaveBeenCalled(); + expect((outlet).spy('activate')).toHaveBeenCalled(); async.done(); }); })); @@ -310,13 +312,13 @@ class DummyComponent {} class DummyParentComp { } -function makeDummyOutlet() { +function makeDummyOutlet(): RouterOutlet { var ref = new SpyRouterOutlet(); ref.spy('canActivate').andCallFake((_) => PromiseWrapper.resolve(true)); ref.spy('routerCanReuse').andCallFake((_) => PromiseWrapper.resolve(false)); ref.spy('routerCanDeactivate').andCallFake((_) => PromiseWrapper.resolve(true)); ref.spy('activate').andCallFake((_) => PromiseWrapper.resolve(true)); - return ref; + return ref; } class AppCmp {} diff --git a/modules/angular2_material/src/components/dialog/dialog.ts b/modules/angular2_material/src/components/dialog/dialog.ts index d78bc8792a..73f0e593d8 100644 --- a/modules/angular2_material/src/components/dialog/dialog.ts +++ b/modules/angular2_material/src/components/dialog/dialog.ts @@ -21,6 +21,7 @@ import {isPresent, Type} from 'angular2/src/facade/lang'; import {DOM} from 'angular2/src/platform/dom/dom_adapter'; import {MouseEvent, KeyboardEvent} from 'angular2/src/facade/browser'; import {KeyCodes} from 'angular2_material/src/core/key_codes'; +import {PromiseCompleter} from 'angular2/src/facade/promise'; // TODO(jelbourn): Opener of dialog can control where it is rendered. // TODO(jelbourn): body scrolling is disabled while dialog is open. @@ -61,7 +62,7 @@ export class MdDialog { // First, load the MdDialogContainer, into which the given component will be loaded. return this.componentLoader.loadNextToLocation(MdDialogContainer, elementRef) - .then(containerRef => { + .then /**/ ((containerRef: ComponentRef) => { // TODO(tbosch): clean this up when we have custom renderers // (https://github.com/angular/angular/issues/1807) // TODO(jelbourn): Don't use direct DOM access. Need abstraction to create an element @@ -84,7 +85,7 @@ export class MdDialog { // Now load the given component into the MdDialogContainer. return this.componentLoader.loadNextToLocation(type, containerRef.instance.contentRef, bindings) - .then(contentRef => { + .then((contentRef: ComponentRef) => { // Wrap both component refs for the container and the content so that we can return // the `instance` of the content but the dispose method of the container back to the @@ -92,7 +93,7 @@ export class MdDialog { dialogRef.contentRef = contentRef; containerRef.instance.dialogRef = dialogRef; - backdropRefPromise.then(backdropRef => { + backdropRefPromise.then((backdropRef: ComponentRef) => { dialogRef.whenClosed.then((_) => { backdropRef.dispose(); }); }); @@ -104,7 +105,7 @@ export class MdDialog { /** Loads the dialog backdrop (transparent overlay over the rest of the page). */ _openBackdrop(elementRef: ElementRef, bindings: ResolvedProvider[]): Promise { return this.componentLoader.loadNextToLocation(MdBackdrop, elementRef, bindings) - .then((componentRef) => { + .then((componentRef: ComponentRef) => { // TODO(tbosch): clean this up when we have custom renderers // (https://github.com/angular/angular/issues/1807) var backdropElement = componentRef.location.nativeElement; @@ -139,10 +140,10 @@ export class MdDialogRef { isClosed: boolean; // Deferred resolved when the dialog is closed. The promise for this deferred is publicly exposed. - whenClosedDeferred: any; + whenClosedDeferred: PromiseCompleter; // Deferred resolved when the content ComponentRef is set. Only used internally. - contentRefDeferred: any; + contentRefDeferred: PromiseCompleter; constructor() { this._contentRef = null; diff --git a/modules/benchpress/src/runner.ts b/modules/benchpress/src/runner.ts index ff0daabd75..9c0d00ada1 100644 --- a/modules/benchpress/src/runner.ts +++ b/modules/benchpress/src/runner.ts @@ -33,7 +33,9 @@ export class Runner { this._defaultBindings = defaultBindings; } - sample({id, execute, prepare, microMetrics, bindings}): Promise { + sample({id, execute, prepare, microMetrics, bindings}: + {id: string, execute?: any, prepare?: any, microMetrics?: any, bindings?: any}): + Promise { var sampleBindings = [ _DEFAULT_PROVIDERS, this._defaultBindings, diff --git a/modules/benchpress/src/sampler.ts b/modules/benchpress/src/sampler.ts index 7742be351d..e7cec72f21 100644 --- a/modules/benchpress/src/sampler.ts +++ b/modules/benchpress/src/sampler.ts @@ -62,8 +62,8 @@ export class Sampler { return loop(new SampleState([], null)); } - _iterate(lastState) { - var resultPromise; + _iterate(lastState): Promise { + var resultPromise: Promise; if (isPresent(this._prepare)) { resultPromise = this._driver.waitFor(this._prepare); } else { diff --git a/modules/benchpress/test/metric/perflog_metric_spec.ts b/modules/benchpress/test/metric/perflog_metric_spec.ts index 6e8419ca4f..44fa94a746 100644 --- a/modules/benchpress/test/metric/perflog_metric_spec.ts +++ b/modules/benchpress/test/metric/perflog_metric_spec.ts @@ -39,7 +39,7 @@ export function main() { captureFrames?: boolean, receivedData?: boolean, requestCount?: boolean - } = {}) { + } = {}): Metric { commandLog = []; if (isBlank(perfLogFeatures)) { perfLogFeatures = @@ -384,7 +384,7 @@ export function main() { aggregate( [eventFactory.instant('frame', 4), eventFactory.markEnd('frameCapture', 5)], {captureFrames: true}), - (err) => { + (err): any => { expect(() => { throw err; }) .toThrowError('missing start event for frame capture'); async.done(); @@ -396,7 +396,7 @@ export function main() { aggregate( [eventFactory.markStart('frameCapture', 3), eventFactory.instant('frame', 4)], {captureFrames: true}), - (err) => { + (err): any => { expect(() => { throw err; }).toThrowError('missing end event for frame capture'); async.done(); }); @@ -410,7 +410,7 @@ export function main() { eventFactory.markStart('frameCapture', 4) ], {captureFrames: true}), - (err) => { + (err): any => { expect(() => { throw err; }) .toThrowError('can capture frames only once per benchmark run'); async.done(); @@ -424,12 +424,13 @@ export function main() { .toThrowError( 'found start event for frame capture, but frame capture was not requested in benchpress'); async.done(); + return null; }); })); it('should throw if frame capture is enabled, but nothing is captured', inject([AsyncTestCompleter], (async) => { - PromiseWrapper.catchError(aggregate([], {captureFrames: true}), (err) => { + PromiseWrapper.catchError(aggregate([], {captureFrames: true}), (err): any => { expect(() => { throw err; }) .toThrowError( 'frame capture requested in benchpress, but no start event was found'); diff --git a/modules/benchpress/test/runner_spec.ts b/modules/benchpress/test/runner_spec.ts index fe7af2ee20..888971881c 100644 --- a/modules/benchpress/test/runner_spec.ts +++ b/modules/benchpress/test/runner_spec.ts @@ -31,7 +31,7 @@ export function main() { var injector: Injector; var runner; - function createRunner(defaultBindings = null) { + function createRunner(defaultBindings = null): Runner { if (isBlank(defaultBindings)) { defaultBindings = []; } diff --git a/modules/benchpress/test/sampler_spec.ts b/modules/benchpress/test/sampler_spec.ts index cbdfe675af..971b48fffd 100644 --- a/modules/benchpress/test/sampler_spec.ts +++ b/modules/benchpress/test/sampler_spec.ts @@ -31,7 +31,7 @@ export function main() { var EMPTY_EXECUTE = () => {}; describe('sampler', () => { - var sampler; + var sampler: Sampler; function createSampler({driver, metric, reporter, validator, prepare, execute}: { driver?: any, diff --git a/modules/benchpress/test/webdriver/chrome_driver_extension_spec.ts b/modules/benchpress/test/webdriver/chrome_driver_extension_spec.ts index e96133b951..1dd974332b 100644 --- a/modules/benchpress/test/webdriver/chrome_driver_extension_spec.ts +++ b/modules/benchpress/test/webdriver/chrome_driver_extension_spec.ts @@ -49,7 +49,7 @@ export function main() { var normEvents = new TraceEventFactory('timeline', 'pid0'); function createExtension(perfRecords = null, userAgent = null, - messageMethod = 'Tracing.dataCollected') { + messageMethod = 'Tracing.dataCollected'): WebDriverExtension { if (isBlank(perfRecords)) { perfRecords = []; } @@ -85,7 +85,7 @@ export function main() { it('should mark the timeline via console.timeEnd()', inject([AsyncTestCompleter], (async) => { createExtension() - .timeEnd('someName') + .timeEnd('someName', null) .then((_) => { expect(log).toEqual([['executeScript', `console.timeEnd('someName');`]]); async.done(); @@ -467,7 +467,7 @@ export function main() { benchmarkEvents.instant('BenchmarkInstrumentation::ImplThreadRenderingStats', 1100, {'data': {'frame_count': 2}}) ]).readPerfLog(), - (err) => { + (err): any => { expect(() => { throw err; }) .toThrowError('multi-frame render stats not supported'); async.done(); @@ -502,7 +502,7 @@ export function main() { ], CHROME45_USER_AGENT, 'Tracing.bufferUsage') .readPerfLog(), - (err) => { + (err): any => { expect(() => { throw err; }) .toThrowError('The DevTools trace buffer filled during the test!'); async.done(); diff --git a/modules/benchpress/test/webdriver/ios_driver_extension_spec.ts b/modules/benchpress/test/webdriver/ios_driver_extension_spec.ts index c12c156034..39131eeb02 100644 --- a/modules/benchpress/test/webdriver/ios_driver_extension_spec.ts +++ b/modules/benchpress/test/webdriver/ios_driver_extension_spec.ts @@ -32,7 +32,7 @@ export function main() { var normEvents = new TraceEventFactory('timeline', 'pid0'); - function createExtension(perfRecords = null) { + function createExtension(perfRecords = null): WebDriverExtension { if (isBlank(perfRecords)) { perfRecords = []; } @@ -61,7 +61,7 @@ export function main() { it('should mark the timeline via console.timeEnd()', inject([AsyncTestCompleter], (async) => { createExtension() - .timeEnd('someName') + .timeEnd('someName', null) .then((_) => { expect(log).toEqual([['executeScript', `console.timeEnd('someName');`]]); async.done(); diff --git a/modules/playground/src/model_driven_forms/index.ts b/modules/playground/src/model_driven_forms/index.ts index 727fbf5203..9c05b4e508 100644 --- a/modules/playground/src/model_driven_forms/index.ts +++ b/modules/playground/src/model_driven_forms/index.ts @@ -12,11 +12,12 @@ import { import {Component, Directive, View, Host} from 'angular2/core'; import {RegExpWrapper, print, isPresent} from 'angular2/src/facade/lang'; +import {AbstractControl} from 'angular2/common'; /** * Custom validator. */ -function creditCardValidator(c): {[key: string]: boolean} { +function creditCardValidator(c: AbstractControl): {[key: string]: boolean} { if (isPresent(c.value) && RegExpWrapper.test(/^\d{16}$/g, c.value)) { return null; } else { diff --git a/modules/playground/src/routing/inbox-app.ts b/modules/playground/src/routing/inbox-app.ts index 1ec5576e81..d8a0d63751 100644 --- a/modules/playground/src/routing/inbox-app.ts +++ b/modules/playground/src/routing/inbox-app.ts @@ -9,9 +9,9 @@ import { RouteParams } from 'angular2/router'; import * as db from './data'; -import {ObservableWrapper, PromiseWrapper} from 'angular2/src/facade/async'; -import {ListWrapper} from 'angular2/src/facade/collection'; +import {PromiseWrapper} from 'angular2/src/facade/async'; import {isPresent, DateWrapper} from 'angular2/src/facade/lang'; +import {PromiseCompleter} from 'angular2/src/facade/promise'; class InboxRecord { id: string = ''; @@ -60,31 +60,31 @@ class InboxRecord { @Injectable() class DbService { getData(): Promise { - var p = PromiseWrapper.completer(); + var p = new PromiseCompleter(); p.resolve(db.data); return p.promise; } drafts(): Promise { - return PromiseWrapper.then(this.getData(), (data: any[]) => { - return data.filter(record => isPresent(record['draft']) && record['draft'] == true); - }); + return this.getData().then( + (data: any[]): any[] => + data.filter(record => isPresent(record['draft']) && record['draft'] == true)); } emails(): Promise { - return PromiseWrapper.then(this.getData(), (data: any[]) => { - return data.filter(record => !isPresent(record['draft'])); - }); + return this.getData().then((data: any[]): any[] => + data.filter(record => !isPresent(record['draft']))); } email(id): Promise { - return PromiseWrapper.then(this.getData(), (data) => { + return PromiseWrapper.then(this.getData(), (data: any[]) => { for (var i = 0; i < data.length; i++) { var entry = data[i]; if (entry['id'] == id) { return entry; } } + return null; }); } } @@ -109,16 +109,16 @@ class InboxCmp { var sortType = params.get('sort'); var sortEmailsByDate = isPresent(sortType) && sortType == "date"; - PromiseWrapper.then(db.emails(), emails => { + PromiseWrapper.then(db.emails(), (emails: any[]) => { this.ready = true; this.items = emails.map(data => new InboxRecord(data)); if (sortEmailsByDate) { - ListWrapper.sort(this.items, - (a, b) => DateWrapper.toMillis(DateWrapper.fromISOString(a.date)) < - DateWrapper.toMillis(DateWrapper.fromISOString(b.date)) ? - -1 : - 1); + this.items.sort((a: InboxRecord, b: InboxRecord) => + DateWrapper.toMillis(DateWrapper.fromISOString(a.date)) < + DateWrapper.toMillis(DateWrapper.fromISOString(b.date)) ? + -1 : + 1); } }); } @@ -131,7 +131,7 @@ class DraftsCmp { ready: boolean = false; constructor(public router: Router, db: DbService) { - PromiseWrapper.then(db.drafts(), (drafts) => { + PromiseWrapper.then(db.drafts(), (drafts: any[]) => { this.ready = true; this.items = drafts.map(data => new InboxRecord(data)); }); diff --git a/modules/playground/src/todo/index.ts b/modules/playground/src/todo/index.ts index ae1eb14c4a..4cf77646b3 100644 --- a/modules/playground/src/todo/index.ts +++ b/modules/playground/src/todo/index.ts @@ -8,7 +8,7 @@ import {Store, Todo, TodoFactory} from './services/TodoStore'; class TodoApp { todoEdit: Todo = null; - constructor(public todoStore: Store, public factory: TodoFactory) {} + constructor(public todoStore: Store, public factory: TodoFactory) {} enterTodo(inputElement): void { this.addTodo(inputElement.value); diff --git a/modules/playground/src/todo/services/TodoStore.ts b/modules/playground/src/todo/services/TodoStore.ts index 3c031c4132..aae2371c13 100644 --- a/modules/playground/src/todo/services/TodoStore.ts +++ b/modules/playground/src/todo/services/TodoStore.ts @@ -2,7 +2,7 @@ import {Injectable} from 'angular2/core'; import {ListWrapper, Predicate} from 'angular2/src/facade/collection'; // base model for RecordStore -export class KeyModel { +export abstract class KeyModel { constructor(public key: number) {} } @@ -23,19 +23,19 @@ export class TodoFactory { // Store manages any generic item that inherits from KeyModel @Injectable() -export class Store { - list: KeyModel[] = []; +export class Store { + list: T[] = []; - add(record: KeyModel): void { this.list.push(record); } + add(record: T): void { this.list.push(record); } - remove(record: KeyModel): void { this._spliceOut(record); } + remove(record: T): void { this._spliceOut(record); } - removeBy(callback: Predicate): void { + removeBy(callback: Predicate): void { var records = this.list.filter(callback); ListWrapper.removeAll(this.list, records); } - private _spliceOut(record: KeyModel) { + private _spliceOut(record: T) { var i = this._indexFor(record); if (i > -1) { return ListWrapper.splice(this.list, i, 1)[0]; @@ -43,5 +43,5 @@ export class Store { return null; } - private _indexFor(record: KeyModel) { return this.list.indexOf(record); } + private _indexFor(record: T) { return this.list.indexOf(record); } } diff --git a/modules_dart/transform/lib/src/transform/template_compiler/change_detector_codegen.dart b/modules_dart/transform/lib/src/transform/template_compiler/change_detector_codegen.dart index 237012983f..fa65adae01 100644 --- a/modules_dart/transform/lib/src/transform/template_compiler/change_detector_codegen.dart +++ b/modules_dart/transform/lib/src/transform/template_compiler/change_detector_codegen.dart @@ -225,7 +225,7 @@ class _CodegenState { List codes = []; _endOfBlockIdxs.clear(); - ListWrapper.forEachWithIndex(eb.records, (_, i) { + ListWrapper.forEachWithIndex(eb.records, (ProtoRecord _, int i) { var code; var r = eb.records[i]; diff --git a/npm-shrinkwrap.clean.json b/npm-shrinkwrap.clean.json index 8796c25f03..c9d504c470 100644 --- a/npm-shrinkwrap.clean.json +++ b/npm-shrinkwrap.clean.json @@ -1887,7 +1887,7 @@ "version": "4.0.1" }, "dart-style": { - "version": "0.2.6" + "version": "0.2.7" }, "dart2jsaas": { "version": "0.0.16", @@ -5356,7 +5356,7 @@ } }, "ts2dart": { - "version": "0.7.24", + "version": "0.7.31", "dependencies": { "source-map": { "version": "0.4.4" @@ -5839,5 +5839,5 @@ } }, "name": "angular-srcs", - "version": "2.0.0-beta.6" + "version": "2.0.0-beta.8" } diff --git a/npm-shrinkwrap.json b/npm-shrinkwrap.json index 6c738a6893..878526ea0b 100644 --- a/npm-shrinkwrap.json +++ b/npm-shrinkwrap.json @@ -1,6 +1,6 @@ { "name": "angular-srcs", - "version": "2.0.0-beta.6", + "version": "2.0.0-beta.8", "dependencies": { "abbrev": { "version": "1.0.7", @@ -2961,9 +2961,9 @@ "resolved": "https://registry.npmjs.org/dargs/-/dargs-4.0.1.tgz" }, "dart-style": { - "version": "0.2.6", + "version": "0.2.7", "from": "dart-style@>=0.2.6 <0.3.0", - "resolved": "https://registry.npmjs.org/dart-style/-/dart-style-0.2.6.tgz" + "resolved": "https://registry.npmjs.org/dart-style/-/dart-style-0.2.7.tgz" }, "dart2jsaas": { "version": "0.0.16", @@ -8536,9 +8536,9 @@ } }, "ts2dart": { - "version": "0.7.24", - "from": "ts2dart@0.7.24", - "resolved": "https://registry.npmjs.org/ts2dart/-/ts2dart-0.7.24.tgz", + "version": "0.7.31", + "from": "ts2dart@0.7.31", + "resolved": "https://registry.npmjs.org/ts2dart/-/ts2dart-0.7.31.tgz", "dependencies": { "source-map": { "version": "0.4.4", @@ -9310,7 +9310,8 @@ }, "zone.js": { "version": "0.5.15", - "from": "zone.js@0.5.15" + "from": "zone.js@0.5.15", + "resolved": "https://registry.npmjs.org/zone.js/-/zone.js-0.5.15.tgz" } } } diff --git a/package.json b/package.json index d1bbf3465c..0e9a0511dc 100644 --- a/package.json +++ b/package.json @@ -112,7 +112,7 @@ "systemjs-builder": "^0.10.3", "through2": "^0.6.5", "ts-api-guardian": "0.0.2", - "ts2dart": "^0.7.22", + "ts2dart": "^0.7.31", "tsd": "^0.6.5-beta", "tslint": "^3.2.1", "typescript": "^1.7.3", diff --git a/scripts/ci/build_dart_ddc.sh b/scripts/ci/build_dart_ddc.sh index dff10365b9..c62a2aa500 100755 --- a/scripts/ci/build_dart_ddc.sh +++ b/scripts/ci/build_dart_ddc.sh @@ -11,10 +11,10 @@ source $SCRIPT_DIR/env_dart.sh cd $SCRIPT_DIR/../.. # Variables -DDC_TOTAL_WARNING_CAP="1000" -DDC_TOTAL_ERROR_CAP="11" +DDC_TOTAL_WARNING_CAP="210" +DDC_TOTAL_ERROR_CAP="0" DDC_DIR=`pwd`/tmp/dev_compiler -DDC_VERSION="0.1.14" +DDC_VERSION="0.1.20" # Get DDC mkdir -p tmp @@ -78,21 +78,27 @@ then fi cat $LOG_FILE -WARNING_COUNT=`cat $LOG_FILE | wc -l | sed -e 's/^[[:space:]]*//'` +EXIT_CODE=0 + +# TODO remove `grep -v template.dart` after Tobias new compiler lands. + +WARNING_COUNT=$(cat $LOG_FILE | grep -E '^warning.*' | grep -v template.dart | wc -l | sed -e 's/^[[:space:]]*//' || true) +ERROR_COUNT=$(cat $LOG_FILE | grep -E '^severe.*' | wc -l | sed -e 's/^[[:space:]]*//' || true) + + +if [[ "$ERROR_COUNT" -gt "$DDC_TOTAL_ERROR_CAP" ]] +then + echo "Found severe errors in angular2 package" + EXIT_CODE=1 +fi if [[ "$WARNING_COUNT" -gt "$DDC_TOTAL_WARNING_CAP" ]] then echo "Too many warnings: $WARNING_COUNT" - exit 1 + EXIT_CODE=1 else echo "Warning count ok" fi -ERROR_COUNT=`cat $LOG_FILE | grep -E '^severe.*' | wc -l | sed -e 's/^[[:space:]]*//'` -if [[ "$ERROR_COUNT" -gt "$DDC_TOTAL_ERROR_CAP" ]] -then - echo "Found severe errors in angular2 package" - exit 1 -fi - echo 'Dart DDC build finished' +exit $EXIT_CODE diff --git a/scripts/ci/env_dart.sh b/scripts/ci/env_dart.sh index 6eaa0d7fa9..5e6aa481ae 100755 --- a/scripts/ci/env_dart.sh +++ b/scripts/ci/env_dart.sh @@ -66,12 +66,7 @@ if [[ -z $ENV_SET ]]; then fi fi - case "$PLATFORM" in - (Linux) export DART_SDK_LIB_SEARCH_PATH="$DART_SDK" ;; - (Darwin) export DART_SDK_LIB_SEARCH_PATH="$DART_SDK/libexec" ;; - (*) echo Unsupported platform $PLATFORM. Exiting ... >&2 ; exit 3 ;; - esac - + export DART_SDK_LIB_SEARCH_PATH="$DART_SDK" export DART_SDK export DARTSDK export DART diff --git a/tools/public_api_guard/public_api_spec.ts b/tools/public_api_guard/public_api_spec.ts index f0b53555e4..ed1ba08b48 100644 --- a/tools/public_api_guard/public_api_spec.ts +++ b/tools/public_api_guard/public_api_spec.ts @@ -382,7 +382,7 @@ const CORE = [ 'Reflector.isReflectionEnabled():boolean', 'Reflector.listUnusedKeys():any[]', 'Reflector.method(name:string):MethodFn', - 'Reflector.parameters(typeOrFunc:any):any[]', + 'Reflector.parameters(typeOrFunc:any):any[][]', 'Reflector.propMetadata(typeOrFunc:any):{[key:string]:any[]}', 'Reflector.reflectionCapabilities:PlatformReflectionCapabilities', 'Reflector.registerFunction(func:Function, funcInfo:ReflectionInfo):void', @@ -555,7 +555,7 @@ const CORE = [ const COMMON = [ 'AbstractControl', - 'AbstractControl.constructor(validator:Function, asyncValidator:Function)', + 'AbstractControl.constructor(validator:ValidatorFn, asyncValidator:AsyncValidatorFn)', 'AbstractControl.dirty:boolean', 'AbstractControl.errors:{[key:string]:any}', 'AbstractControl.find(path:Array|string):AbstractControl', @@ -599,12 +599,12 @@ const COMMON = [ 'CheckboxControlValueAccessor.registerOnTouched(fn:() => {}):void', 'CheckboxControlValueAccessor.writeValue(value:any):void', 'Control', - 'Control.constructor(value:any, validator:Function, asyncValidator:Function)', + 'Control.constructor(value:any, validator:ValidatorFn, asyncValidator:AsyncValidatorFn)', 'Control.registerOnChange(fn:Function):void', 'Control.updateValue(value:any, {onlySelf,emitEvent,emitModelToViewChange}:{onlySelf?:boolean, emitEvent?:boolean, emitModelToViewChange?:boolean}):void', 'ControlArray', 'ControlArray.at(index:number):AbstractControl', - 'ControlArray.constructor(controls:AbstractControl[], validator:Function, asyncValidator:Function)', + 'ControlArray.constructor(controls:AbstractControl[], validator:ValidatorFn, asyncValidator:AsyncValidatorFn)', 'ControlArray.insert(index:number, control:AbstractControl):void', 'ControlArray.length:number', 'ControlArray.push(control:AbstractControl):void', @@ -615,7 +615,7 @@ const COMMON = [ 'ControlContainer.path:string[]', 'ControlGroup', 'ControlGroup.addControl(name:string, control:AbstractControl):void', - 'ControlGroup.constructor(controls:{[key:string]:AbstractControl}, optionals:{[key:string]:boolean}, validator:Function, asyncValidator:Function)', + 'ControlGroup.constructor(controls:{[key:string]:AbstractControl}, optionals:{[key:string]:boolean}, validator:ValidatorFn, asyncValidator:AsyncValidatorFn)', 'ControlGroup.contains(controlName:string):boolean', 'ControlGroup.exclude(controlName:string):void', 'ControlGroup.include(controlName:string):void', @@ -647,8 +647,8 @@ const COMMON = [ 'Form.removeControlGroup(dir:NgControlGroup):void', 'Form.updateModel(dir:NgControl, value:any):void', 'FormBuilder', - 'FormBuilder.array(controlsConfig:any[], validator:Function, asyncValidator:Function):ControlArray', - 'FormBuilder.control(value:Object, validator:Function, asyncValidator:Function):Control', + 'FormBuilder.array(controlsConfig:any[], validator:ValidatorFn, asyncValidator:AsyncValidatorFn):ControlArray', + 'FormBuilder.control(value:Object, validator:ValidatorFn, asyncValidator:AsyncValidatorFn):Control', 'FormBuilder.group(controlsConfig:{[key:string]:any}, extra:{[key:string]:any}):ControlGroup', 'I18nPluralPipe', 'I18nPluralPipe.transform(value:number, args:any[]):string', @@ -660,10 +660,10 @@ const COMMON = [ 'LowerCasePipe.transform(value:string, args:any[]):string', 'MaxLengthValidator', 'MaxLengthValidator.constructor(maxLength:string)', - 'MaxLengthValidator.validate(c:Control):{[key:string]:any}', + 'MaxLengthValidator.validate(c:AbstractControl):{[key:string]:any}', 'MinLengthValidator', 'MinLengthValidator.constructor(minLength:string)', - 'MinLengthValidator.validate(c:Control):{[key:string]:any}', + 'MinLengthValidator.validate(c:AbstractControl):{[key:string]:any}', 'NgClass', 'NgClass.constructor(_iterableDiffers:IterableDiffers, _keyValueDiffers:KeyValueDiffers, _ngEl:ElementRef, _renderer:Renderer)', 'NgClass.initialClasses=(v:string)', @@ -671,22 +671,22 @@ const COMMON = [ 'NgClass.ngOnDestroy():void', 'NgClass.rawClass=(v:string|string[]|Set|{[key:string]:any})', 'NgControl', - 'NgControl.asyncValidator:Function', + 'NgControl.asyncValidator:AsyncValidatorFn', 'NgControl.name:string', - 'NgControl.validator:Function', + 'NgControl.validator:ValidatorFn', 'NgControl.valueAccessor:ControlValueAccessor', 'NgControl.viewToModelUpdate(newValue:any):void', 'NgControlGroup', - 'NgControlGroup.asyncValidator:Function', + 'NgControlGroup.asyncValidator:AsyncValidatorFn', 'NgControlGroup.constructor(parent:ControlContainer, _validators:any[], _asyncValidators:any[])', 'NgControlGroup.control:ControlGroup', 'NgControlGroup.formDirective:Form', 'NgControlGroup.ngOnDestroy():void', 'NgControlGroup.ngOnInit():void', 'NgControlGroup.path:string[]', - 'NgControlGroup.validator:Function', + 'NgControlGroup.validator:ValidatorFn', 'NgControlName', - 'NgControlName.asyncValidator:Function', + 'NgControlName.asyncValidator:AsyncValidatorFn', 'NgControlName.constructor(_parent:ControlContainer, _validators:any[], _asyncValidators:any[], valueAccessors:ControlValueAccessor[])', 'NgControlName.control:Control', 'NgControlName.formDirective:any', @@ -695,7 +695,7 @@ const COMMON = [ 'NgControlName.ngOnDestroy():void', 'NgControlName.path:string[]', 'NgControlName.update:any', - 'NgControlName.validator:Function', + 'NgControlName.validator:ValidatorFn', 'NgControlName.viewModel:any', 'NgControlName.viewToModelUpdate(newValue:any):void', 'NgControlStatus', @@ -729,7 +729,7 @@ const COMMON = [ 'NgForm.removeControlGroup(dir:NgControlGroup):void', 'NgForm.updateModel(dir:NgControl, value:any):void', 'NgFormControl', - 'NgFormControl.asyncValidator:Function', + 'NgFormControl.asyncValidator:AsyncValidatorFn', 'NgFormControl.constructor(_validators:any[], _asyncValidators:any[], valueAccessors:ControlValueAccessor[])', 'NgFormControl.control:Control', 'NgFormControl.form:Control', @@ -737,7 +737,7 @@ const COMMON = [ 'NgFormControl.ngOnChanges(changes:{[key:string]:SimpleChange}):void', 'NgFormControl.path:string[]', 'NgFormControl.update:any', - 'NgFormControl.validator:Function', + 'NgFormControl.validator:ValidatorFn', 'NgFormControl.viewModel:any', 'NgFormControl.viewToModelUpdate(newValue:any):void', 'NgFormModel', @@ -761,14 +761,14 @@ const COMMON = [ 'NgIf.constructor(_viewContainer:ViewContainerRef, _templateRef:TemplateRef)', 'NgIf.ngIf=(newCondition:any)', 'NgModel', - 'NgModel.asyncValidator:Function', + 'NgModel.asyncValidator:AsyncValidatorFn', 'NgModel.constructor(_validators:any[], _asyncValidators:any[], valueAccessors:ControlValueAccessor[])', 'NgModel.control:Control', 'NgModel.model:any', 'NgModel.ngOnChanges(changes:{[key:string]:SimpleChange}):any', 'NgModel.path:string[]', 'NgModel.update:any', - 'NgModel.validator:Function', + 'NgModel.validator:ValidatorFn', 'NgModel.viewModel:any', 'NgModel.viewToModelUpdate(newValue:any):void', 'NgSelectOption', @@ -786,7 +786,7 @@ const COMMON = [ 'NumberPipe', 'PatternValidator', 'PatternValidator.constructor(pattern:string)', - 'PatternValidator.validate(c:Control):{[key:string]:any}', + 'PatternValidator.validate(c:AbstractControl):{[key:string]:any}', 'PercentPipe', 'PercentPipe.transform(value:any, args:any[]):string', 'ReplacePipe', @@ -805,15 +805,15 @@ const COMMON = [ 'UpperCasePipe', 'UpperCasePipe.transform(value:string, args:any[]):string', 'Validator', - 'Validator.validate(c:Control):{[key:string]:any}', + 'Validator.validate(c:AbstractControl):{[key:string]:any}', 'Validators', - 'Validators.compose(validators:Function[]):Function', - 'Validators.composeAsync(validators:Function[]):Function', - 'Validators.maxLength(maxLength:number):Function', - 'Validators.minLength(minLength:number):Function', - 'Validators.nullValidator(c:any):{[key:string]:boolean}', - 'Validators.pattern(pattern:string):Function', - 'Validators.required(control:Control):{[key:string]:boolean}', + 'Validators.compose(validators:ValidatorFn[]):ValidatorFn', + 'Validators.composeAsync(validators:AsyncValidatorFn[]):AsyncValidatorFn', + 'Validators.maxLength(maxLength:number):ValidatorFn', + 'Validators.minLength(minLength:number):ValidatorFn', + 'Validators.nullValidator(c:AbstractControl):{[key:string]:boolean}', + 'Validators.pattern(pattern:string):ValidatorFn', + 'Validators.required(control:AbstractControl):{[key:string]:boolean}', 'RadioButtonState', 'RadioButtonState.constructor(checked:boolean, value:string)', 'const COMMON_DIRECTIVES:Type[][]',