diff --git a/types/ember-testing-helpers/ember-testing-helpers-tests.ts b/types/ember-testing-helpers/ember-testing-helpers-tests.ts index 9088097b25..70ff59a2d8 100644 --- a/types/ember-testing-helpers/ember-testing-helpers-tests.ts +++ b/types/ember-testing-helpers/ember-testing-helpers-tests.ts @@ -1,10 +1,12 @@ +import RSVP from 'rsvp'; + function testAndThen() { - const result: RSVP.Promise = andThen(() => "some string"); + const result: RSVP.Promise = andThen(() => 'some string'); result.then(s => s.length); } function testClick() { - const result: RSVP.Promise = click('someString'); + const result: RSVP.Promise = click('someString'); result.then(() => {}); } @@ -26,7 +28,7 @@ function testCurrentURL() { function testFillIn() { const textResult = fillIn('.foo', 'waffles'); textResult.then(() => true); - const contextResult = fillIn('.bar', { }, 'pancakes'); + const contextResult = fillIn('.bar', {}, 'pancakes'); contextResult.catch(reason => false); } @@ -55,7 +57,7 @@ function testKeyEvent() { function testPauseTest() { pauseTest().finally(() => { const foo = 'fighters'; - }) + }); } function testResumeTest() { @@ -70,7 +72,7 @@ function testTriggerEvent() { } function testVisit() { - visit('some/url').then(() => {}) + visit('some/url').then(() => {}); } function testWait() { diff --git a/types/ember-testing-helpers/index.d.ts b/types/ember-testing-helpers/index.d.ts index 3fd1d4e23f..e45d844487 100644 --- a/types/ember-testing-helpers/index.d.ts +++ b/types/ember-testing-helpers/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for ember-testing/lib/helpers -// Project: Ember.js Testing Helpers: https://github.com/emberjs/ember.js/tree/master/packages/ember-testing/lib/helpers +// Project: https://github.com/emberjs/ember.js/tree/master/packages/ember-testing/lib/helpers // Definitions by: Chris Krycho // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -9,55 +9,61 @@ // not easily or straightforwardly exported from the Ember type definitions. /// -/// + +import RSVP from 'rsvp'; type KeyEventType = 'keydown' | 'keyup' | 'keypress'; -type VoidWaitResult = RSVP.Promise; +type WaitResult = RSVP.Promise; declare global { - // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/and_then.js - function andThen(callback: (...args: any[]) => T): RSVP.Promise; + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/and_then.js + function andThen(callback: (...args: any[]) => T): RSVP.Promise; - // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/click.js - function click(selector: string, context?: Object): VoidWaitResult; + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/click.js + function click(selector: string, context?: Object): WaitResult; - // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/current_path.js - function currentPath(): string; + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/current_path.js + function currentPath(): string; - // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/current_route_name.js - function currentRouteName(): string; + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/current_route_name.js + function currentRouteName(): string; - // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/current_url.js - function currentURL(): string; + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/current_url.js + function currentURL(): string; - // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/fill_in.js - function fillIn(selector: string, context: Object, text: string): VoidWaitResult; - function fillIn(selector: string, text: string): VoidWaitResult; + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/fill_in.js + function fillIn(selector: string, context: Object, text: string): WaitResult; + function fillIn(selector: string, text: string): WaitResult; - // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/find.js - function find(selector: string, context?: Object): JQuery; + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/find.js + function find(selector: string, context?: Object): JQuery; - // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/find_with_assert.js - function findWithAssert(selector: string, context?: Object): JQuery; + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/find_with_assert.js + function findWithAssert(selector: string, context?: Object): JQuery; - // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/key_event.js - function keyEvent(selector: string, type: KeyEventType, keyCode: number): VoidWaitResult; + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/key_event.js + function keyEvent(selector: string, type: KeyEventType, keyCode: number): WaitResult; - // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/pause_test.js - function pauseTest(): RSVP.Promise<{}>; - function resumeTest(): void; + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/pause_test.js + function pauseTest(): RSVP.Promise<{}, never>; + function resumeTest(): void; - // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/trigger_event.js - function triggerEvent(selector: string, context: Object, type: string, options: Object): VoidWaitResult; - function triggerEvent(selector: string, context: Object, type: string): VoidWaitResult; - function triggerEvent(selector: string, type: string, options: Object): VoidWaitResult; - function triggerEvent(selector: string, type: string): VoidWaitResult; + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/trigger_event.js + function triggerEvent( + selector: string, + context: Object, + type: string, + options: Object + ): WaitResult; + function triggerEvent(selector: string, context: Object, type: string): WaitResult; + function triggerEvent(selector: string, type: string, options: Object): WaitResult; + function triggerEvent(selector: string, type: string): WaitResult; - // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/visit.js - function visit(route: string): VoidWaitResult; + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/visit.js + function visit(route: string): WaitResult; - // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/wait.js - function wait(value: T): RSVP.Promise; + // https://github.com/emberjs/ember.js/blob/master/packages/ember-testing/lib/helpers/wait.js + function wait(value: T): WaitResult; } export {}; diff --git a/types/ember/ember-tests.ts b/types/ember/ember-tests.ts index 4119e1d7ec..b5097848ff 100644 --- a/types/ember/ember-tests.ts +++ b/types/ember/ember-tests.ts @@ -1,183 +1,188 @@ +import Ember from 'ember'; + let App: any; -App = Em.Application.create(); +App = Ember.Application.create(); -App.president = Em.Object.create({ - name: 'Barack Obama' +App.president = Ember.Object.create({ + name: 'Barack Obama', }); -App.country = Em.Object.create({ - presidentNameBinding: 'MyApp.president.name' +App.country = Ember.Object.create({ + presidentNameBinding: 'MyApp.president.name', }); App.country.get('presidentName'); -App.president = Em.Object.create({ +App.president = Ember.Object.create({ firstName: 'Barack', lastName: 'Obama', - fullName: function() { + fullName: Ember.computed(function() { return this.get('firstName') + ' ' + this.get('lastName'); - }.property() + }), }); App.president.get('fullName'); -declare class MyPerson extends Em.Object { +declare class MyPerson extends Ember.Object { static createMan(): MyPerson; } -const Person1 = Em.Object.extend({ +const Person1 = Ember.Object.extend({ say: (thing: string) => { alert(thing); - } + }, }); -declare class MyPerson2 extends Em.Object { +declare class MyPerson2 extends Ember.Object { helloWorld(): void; } const tom = Person1.create({ name: 'Tom Dale', helloWorld() { this.say('Hi my name is ' + this.get('name')); - } + }, }); tom.helloWorld(); Person1.reopen({ isPerson: true }); -Person1.create().get('isPerson'); +Person1.create().get('isPerson'); Person1.reopenClass({ createMan: () => { return Person1.create({ isMan: true }); - } + }, }); // ReSharper disable once DuplicatingLocalDeclaration Person1.createMan().get('isMan'); -const person = Person1.create({ +const person = Person1.create({ firstName: 'Yehuda', - lastName: 'Katz' + lastName: 'Katz', }); -person.addObserver('fullName', null, () => { }); +person.addObserver('fullName', null, () => {}); person.set('firstName', 'Brohuda'); -App.todosController = Em.Object.create({ - todos: [ - Em.Object.create({ isDone: false }) - ], - remaining: (function() { +App.todosController = Ember.Object.create({ + todos: [Ember.Object.create({ isDone: false })], + remaining: Ember.computed('todos.@each.isDone', function() { const todos = this.get('todos'); return todos.filterProperty('isDone', false).get('length'); - }).property('todos.@each.isDone') + }), }); const todos = App.todosController.get('todos'); let todo = todos.objectAt(0); todo.set('isDone', true); App.todosController.get('remaining'); -todo = Em.Object.create({ isDone: false }); +todo = Ember.Object.create({ isDone: false }); todos.pushObject(todo); App.todosController.get('remaining'); -App.wife = Em.Object.create({ - householdIncome: 80000 +App.wife = Ember.Object.create({ + householdIncome: 80000, }); -App.husband = Em.Object.create({ - householdIncomeBinding: 'App.wife.householdIncome' +App.husband = Ember.Object.create({ + householdIncomeBinding: 'App.wife.householdIncome', }); App.husband.get('householdIncome'); App.husband.set('householdIncome', 90000); App.wife.get('householdIncome'); -App.user = Em.Object.create({ - fullName: 'Kara Gates' +App.user = Ember.Object.create({ + fullName: 'Kara Gates', }); App.user.set('fullName', 'Krang Gates'); App.userView.set('userName', 'Truckasaurus Gates'); App.user.get('fullName'); -App = Em.Application.create({ - rootElement: '#sidebar' +App = Ember.Application.create({ + rootElement: '#sidebar', }); -App.userController = Em.Object.create({ - content: Em.Object.create({ +App.userController = Ember.Object.create({ + content: Ember.Object.create({ firstName: 'Albert', lastName: 'Hofmann', posts: 25, - hobbies: 'Riding bicycles' - }) + hobbies: 'Riding bicycles', + }), }); -Ember.Helper.helper((params) => { - let cents = params[0]; - return `${cents * 0.01}`; +Ember.Helper.helper(params => { + let cents = params[0]; + return `${cents * 0.01}`; }); Ember.Helper.helper((params, hash) => { - let cents = params[0]; - let currency = hash.currency; - return `${currency}${cents * 0.01}`; + let cents = params[0]; + let currency = hash.currency; + return `${currency}${cents * 0.01}`; }); -Handlebars.registerHelper('highlight', (property: string, options: any) => - new Handlebars.SafeString('' + "some value" + '')); +Handlebars.registerHelper( + 'highlight', + (property: string, options: any) => + new Handlebars.SafeString('' + 'some value' + '') +); const coolView = App.CoolView.create(); -const Person2 = Em.Object.extend({ +const Person2 = Ember.Object.extend({ sayHello() { console.log('Hello from ' + this.get('name')); - } + }, }); -const people = [ +const people = Ember.A([ Person2.create({ name: 'Juan' }), Person2.create({ name: 'Charles' }), - Person2.create({ name: 'Majd' }) -]; + Person2.create({ name: 'Majd' }), +]); people.invoke('sayHello'); -const arr = [Em.Object.create(), Em.Object.create()]; +const arr = Ember.A([Ember.Object.create(), Ember.Object.create()]); arr.setEach('name', 'unknown'); arr.getEach('name'); -const Person3 = Em.Object.extend({ +const Person3 = Ember.Object.extend({ name: null, - isHappy: false + isHappy: false, }); -const people2 = [ +const people2 = Ember.A([ Person3.create({ name: 'Yehuda', isHappy: true }), - Person3.create({ name: 'Majd', isHappy: false }) -]; -people2.every((person: Em.Object) => { + Person3.create({ name: 'Majd', isHappy: false }), +]); +const isHappy = (person: Ember.Object): Boolean => { return !!person.get('isHappy'); -}); -people2.some((person: Em.Object) => { - return !!person.get('isHappy'); -}); +}; +people2.every(isHappy); +people2.any(isHappy); people2.everyProperty('isHappy', true); people2.someProperty('isHappy', true); // Examples taken from http://emberjs.com/api/classes/Em.RSVP.Promise.html -const promise = new Em.RSVP.Promise((resolve: Function, reject: Function) => { - // on success - resolve('ok!'); +const promise = new Ember.RSVP.Promise((resolve: Function, reject: Function) => { + // on success + resolve('ok!'); - // on failure - reject('no-k!'); + // on failure + reject('no-k!'); }); -promise.then((value: any) => { - // on fulfillment -}, (reason: any) => { - // on rejection -}); +promise.then( + (value: any) => { + // on fulfillment + }, + (reason: any) => { + // on rejection + } +); const mix1 = Ember.Mixin.create({ - foo: 1 + foo: 1, }); const mix2 = Ember.Mixin.create({ - bar: 2 + bar: 2, }); -const component1 = Ember.Component.extend( mix1, mix2, { - lyft: Ember.inject.service(), - cars: Ember.computed.readOnly('lyft.cars') +const component1 = Ember.Component.extend(mix1, mix2, { + lyft: Ember.inject.service(), + cars: Ember.computed.readOnly('lyft.cars'), }); diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index ecb6d26192..56b21e7405 100644 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -3,24 +3,28 @@ // Definitions by: Jed Mao // bttf // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 /// /// +// Capitalization is intentional: this makes it much easier to re-export RSVP on +// the Ember namespace. +import Rsvp from 'rsvp'; + declare namespace EmberStates { interface Transition { targetName: string; urlMethod: string; intent: any; - params: {}|any; + params: {} | any; pivotHandler: any; resolveIndex: number; handlerInfos: any; - resolvedModels: {}|any; + resolvedModels: {} | any; isActive: boolean; state: any; - queryParams: {}|any; + queryParams: {} | any; queryParamsOnly: boolean; isTransition: boolean; @@ -33,7 +37,7 @@ declare namespace EmberStates { Transition object can be externally `abort`ed, while the promise cannot. */ - promise: Ember.RSVP.Promise; + promise: Rsvp.Promise; /** Custom state can be stored on a Transition's `data` object. @@ -57,7 +61,7 @@ declare namespace EmberStates { @arg {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} */ - then(onFulfilled: Function, onRejected?: Function, label?: string): Ember.RSVP.Promise; + then(onFulfilled: Function, onRejected?: Function, label?: string): Rsvp.Promise; /** Forwards to the internal `promise` property which you can @@ -70,7 +74,7 @@ declare namespace EmberStates { Useful for tooling. @return {Promise} */ - catch(onRejection: Function, label?: string): Ember.RSVP.Promise; + catch(onRejection: Function, label?: string): Rsvp.Promise; /** Forwards to the internal `promise` property which you can @@ -83,7 +87,7 @@ declare namespace EmberStates { Useful for tooling. @return {Promise} */ - finally(callback: Function, label?: string): Ember.RSVP.Promise; + finally(callback: Function, label?: string): Rsvp.Promise; /** Aborts the Transition. Note you can also implicitly abort a transition @@ -150,7 +154,7 @@ declare namespace EmberStates { @return {Promise} a promise that fulfills with the same value that the final redirecting transition fulfills with */ - followRedirects(): Ember.RSVP.Promise; + followRedirects(): Rsvp.Promise; } } @@ -165,7 +169,7 @@ declare namespace EmberTesting { exception(error: string): void; } - class QUnitAdapter extends Adapter { } + class QUnitAdapter extends Adapter {} } } @@ -202,16 +206,26 @@ interface Array { clear(): any[]; compact(): any[]; contains(obj: any): boolean; - enumerableContentDidChange(start: number, removing: Ember.Enumerable | number, adding: Ember.Enumerable | number): any; - enumerableContentDidChange(removing: Ember.Enumerable | number, adding: Ember.Enumerable | number): any; - enumerableContentWillChange(removing: Ember.Enumerable | number, adding: Ember.Enumerable | number): Ember.Enumerable; - every(callback: Function, target?: any): boolean; + enumerableContentDidChange( + start: number, + removing: Ember.Enumerable | number, + adding: Ember.Enumerable | number + ): any; + enumerableContentDidChange( + removing: Ember.Enumerable | number, + adding: Ember.Enumerable | number + ): any; + enumerableContentWillChange( + removing: Ember.Enumerable | number, + adding: Ember.Enumerable | number + ): Ember.Enumerable; + every(callback: ItemIndexEnumerableCallback, target?: any): boolean; everyBy(key: string, value?: string): boolean; everyProperty(key: string, value?: any): boolean; filter(callback: Function, target?: any): any[]; filterBy(key: string, value?: string): any[]; - /** + /** Returns the first item in the array for which the callback returns true. This method works similar to the `filter()` method defined in JavaScript 1.6 except that it will stop working on the array once a match is found. @@ -315,7 +329,10 @@ interface ApplicationCreateArguments { LOG_TRANSITIONS_INTERNAL?: boolean; } -type ApplicationInitializerFunction = (container: Ember.Container, application: Ember.Application) => void; +type ApplicationInitializerFunction = ( + container: Ember.Container, + application: Ember.Application +) => void; interface ApplicationInitializerArguments { name?: string; @@ -339,15 +356,23 @@ interface CoreObjectArguments { } interface EnumerableConfigurationOptions { - willChange?: boolean ; - didChange?: boolean ; + willChange?: boolean; + didChange?: boolean; } -type ItemIndexEnumerableCallbackTarget = (callback: ItemIndexEnumerableCallback, target?: any) => any[]; +type ItemIndexEnumerableCallbackTarget = ( + callback: ItemIndexEnumerableCallback, + target?: any +) => any[]; type ItemIndexEnumerableCallback = (item: any, index: number, enumerable: Ember.Enumerable) => void; -type ReduceCallback = (previousValue: any, item: any, index: number, enumerable: Ember.Enumerable) => void; +type ReduceCallback = ( + previousValue: any, + item: any, + index: number, + enumerable: Ember.Enumerable +) => void; interface TransitionsHash { contexts: any[]; @@ -374,7 +399,12 @@ interface RenderOptions { view?: string; } -type ModifyObserver = (obj: any, path: string | null, target: Function | any, method?: Function | string) => void; +type ModifyObserver = ( + obj: any, + path: string | null, + target: Function | any, + method?: Function | string +) => void; declare namespace Ember { /** @@ -512,24 +542,31 @@ declare namespace Ember { class Array implements Enumerable { addArrayObserver(target: any, opts?: EnumerableConfigurationOptions): any[]; addEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; - any(callback: Function, target?: any): boolean; + any(callback: ItemIndexEnumerableCallback, target?: any): boolean; anyBy(key: string, value?: string): boolean; arrayContentDidChange(startIdx: number, removeAmt: number, addAmt: number): any[]; arrayContentWillChange(startIdx: number, removeAmt: number, addAmt: number): any[]; someProperty(key: string, value?: string): boolean; compact(): any[]; contains(obj: any): boolean; - enumerableContentDidChange(start: number, removing: Enumerable | number, adding: Enumerable | number): any; + enumerableContentDidChange( + start: number, + removing: Enumerable | number, + adding: Enumerable | number + ): any; enumerableContentDidChange(removing: Enumerable | number, adding: Enumerable | number): any; - enumerableContentWillChange(removing: Enumerable | number, adding: Enumerable | number): Enumerable; - every(callback: Function, target?: any): boolean; + enumerableContentWillChange( + removing: Enumerable | number, + adding: Enumerable | number + ): Enumerable; + every(callback: ItemIndexEnumerableCallback, target?: any): boolean; everyBy(key: string, value?: string): boolean; everyProperty(key: string, value?: string): boolean; - filter(callback: Function, target: any): any[]; + filter(callback: ItemIndexEnumerableCallback, target: any): any[]; filterBy(key: string, value?: string): any[]; - find(callback: Function, target?: any): any; + find(callback: ItemIndexEnumerableCallback, target?: any): any; findBy(key: string, value?: string): any; - forEach(callback: Function, target?: any): any; + forEach(callback: ItemIndexEnumerableCallback, target?: any): any; getEach(key: string): any[]; indexOf(object: any, startAt: number): number; invoke(methodName: string, ...args: any[]): any[]; @@ -546,7 +583,7 @@ declare namespace Ember { removeEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; setEach(key: string, value?: any): any; slice(beginIndex?: number, endIndex?: number): any[]; - some(callback: Function, target?: any): boolean; + some(callback: ItemIndexEnumerableCallback, target?: any): boolean; toArray(): any[]; uniq(): Enumerable; without(value: any): Enumerable; @@ -580,7 +617,7 @@ declare namespace Ember { static isMethod: boolean; addArrayObserver(target: any, opts?: EnumerableConfigurationOptions): any[]; addEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; - any(callback: Function, target?: any): boolean; + any(callback: ItemIndexEnumerableCallback, target?: any): boolean; anyBy(key: string, value?: string): boolean; arrayContentDidChange(startIdx: number, removeAmt: number, addAmt: number): any[]; arrayContentWillChange(startIdx: number, removeAmt: number, addAmt: number): any[]; @@ -588,17 +625,24 @@ declare namespace Ember { clear(): any[]; compact(): any[]; contains(obj: any): boolean; - enumerableContentDidChange(start: number, removing: Enumerable | number, adding: Enumerable | number): any; + enumerableContentDidChange( + start: number, + removing: Enumerable | number, + adding: Enumerable | number + ): any; enumerableContentDidChange(removing: Enumerable | number, adding: Enumerable | number): any; - enumerableContentWillChange(removing: Enumerable | number, adding: Enumerable | number): Enumerable; - every(callback: Function, target?: any): boolean; + enumerableContentWillChange( + removing: Enumerable | number, + adding: Enumerable | number + ): Enumerable; + every(callback: ItemIndexEnumerableCallback, target?: any): boolean; everyBy(key: string, value?: string): boolean; everyProperty(key: string, value?: string): boolean; - filter(callback: Function, target: any): any[]; + filter(callback: ItemIndexEnumerableCallback, target: any): any[]; filterBy(key: string, value?: string): any[]; - find(callback: Function, target: any): any; + find(callback: ItemIndexEnumerableCallback, $target: any): any; findBy(key: string, value?: string): any; - forEach(callback: Function, target?: any): any; + forEach(callback: ItemIndexEnumerableCallback, target?: any): any; getEach(key: string): any[]; indexOf(object: any, startAt: number): number; insertAt(idx: number, object: any): any[]; @@ -626,7 +670,7 @@ declare namespace Ember { setObjects(objects: any[]): any[]; shiftObject(): any; slice(beginIndex?: number, endIndex?: number): any[]; - some(callback: Function, target?: any): boolean; + some(callback: ItemIndexEnumerableCallback, target?: any): boolean; toArray(): any[]; uniq(): Enumerable; unshiftObject(object: any): any; @@ -877,7 +921,7 @@ declare namespace Ember { @param {Object} [args] - Object containing values to use within the new class Non-static method because Ember classes aren't currently 'real' TypeScript classes. **/ - extend(mixin1 ?: Mixin, mixin2 ?: Mixin, args ?: CoreObjectArguments): T; + extend(mixin1?: Mixin, mixin2?: Mixin, args?: CoreObjectArguments): T; /** Equivalent to doing extend(arguments).create(). If possible use the normal create method instead. @@ -958,7 +1002,7 @@ declare namespace Ember { The default implementation handles simple properties. You generally won't need to create or subclass this directly. **/ - class Descriptor { } + class Descriptor {} namespace ENV { const EXTEND_PROTOTYPES: typeof Ember.EXTEND_PROTOTYPES; const LOG_BINDINGS: boolean; @@ -1002,22 +1046,29 @@ declare namespace Ember { **/ class Enumerable { addEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; - any(callback: Function, target?: any): boolean; + any(callback: ItemIndexEnumerableCallback, target?: any): boolean; anyBy(key: string, value?: string): boolean; someProperty(key: string, value?: string): boolean; compact(): any[]; contains(obj: any): boolean; - enumerableContentDidChange(start: number, removing: Enumerable | number, adding: Enumerable | number): any; + enumerableContentDidChange( + start: number, + removing: Enumerable | number, + adding: Enumerable | number + ): any; enumerableContentDidChange(removing: Enumerable | number, adding: Enumerable | number): any; - enumerableContentWillChange(removing: Enumerable | number, adding: Enumerable | number): Enumerable; - every(callback: Function, target?: any): boolean; + enumerableContentWillChange( + removing: Enumerable | number, + adding: Enumerable | number + ): Enumerable; + every(callback: ItemIndexEnumerableCallback, target?: any): boolean; everyBy(key: string, value?: string): boolean; everyProperty(key: string, value?: string): boolean; - filter(callback: Function, target: any): any[]; + filter(callback: ItemIndexEnumerableCallback, target: any): any[]; filterBy(key: string, value?: string): any[]; - find(callback: Function, target: any): any; + find(callback: ItemIndexEnumerableCallback, target: any): any; findBy(key: string, value?: string): any; - forEach(callback: Function, target?: any): any; + forEach(callback: ItemIndexEnumerableCallback, target?: any): any; getEach(key: string): any[]; invoke(methodName: string, ...args: any[]): any[]; map: ItemIndexEnumerableCallbackTarget; @@ -1028,7 +1079,7 @@ declare namespace Ember { rejectBy(key: string, value?: string): any[]; removeEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; setEach(key: string, value?: any): any; - some(callback: Function, target?: any): boolean; + some(callback: ItemIndexEnumerableCallback, target?: any): boolean; toArray(): any[]; uniq(): Enumerable; without(value: any): Enumerable; @@ -1085,8 +1136,8 @@ declare namespace Ember { function compile(string: string): Function; function compile(environment: any, options?: any, context?: any, asObject?: any): any; function precompile(string: string, options: any): void; - class Compiler { } - class JavaScriptCompiler { } + class Compiler {} + class JavaScriptCompiler {} function registerPartial(name: string, str: any): void; function K(): any; function createFrame(objec: any): any; @@ -1135,13 +1186,13 @@ declare namespace Ember { } const IS_BINDING: RegExp; const inject: { - controller(name?: string): Controller; - service(name?: string): Service; + controller(name?: string): Controller; + service(name?: string): Service; }; class Helper extends Object { - static helper( h: (params: any, hash?: any) => any): Helper; - compute(params: any[], hash: any): any; - recompute(params: any[], hash: any): any; + static helper(h: (params: any, hash?: any) => any): Helper; + compute(params: any[], hash: any): any; + recompute(params: any[], hash: any): any; } class Instrumentation { getProperties(obj: any, list: any[]): {}; @@ -1195,7 +1246,7 @@ declare namespace Ember { class MutableArray implements Array, MutableEnumberable { addArrayObserver(target: any, opts?: EnumerableConfigurationOptions): any[]; addEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; - any(callback: Function, target?: any): boolean; + any(callback: ItemIndexEnumerableCallback, target?: any): boolean; anyBy(key: string, value?: string): boolean; arrayContentDidChange(startIdx: number, removeAmt: number, addAmt: number): any[]; arrayContentWillChange(startIdx: number, removeAmt: number, addAmt: number): any[]; @@ -1203,17 +1254,24 @@ declare namespace Ember { clear(): any[]; compact(): any[]; contains(obj: any): boolean; - enumerableContentDidChange(start: number, removing: Enumerable | number, adding: Enumerable | number): any; + enumerableContentDidChange( + start: number, + removing: Enumerable | number, + adding: Enumerable | number + ): any; enumerableContentDidChange(removing: Enumerable | number, adding: Enumerable | number): any; - enumerableContentWillChange(removing: Enumerable | number, adding: Enumerable | number): Enumerable; - every(callback: Function, target?: any): boolean; + enumerableContentWillChange( + removing: Enumerable | number, + adding: Enumerable | number + ): Enumerable; + every(callback: ItemIndexEnumerableCallback, target?: any): boolean; everyBy(key: string, value?: string): boolean; everyProperty(key: string, value?: string): boolean; - filter(callback: Function, target: any): any[]; + filter(callback: ItemIndexEnumerableCallback, target: any): any[]; filterBy(key: string, value?: string): any[]; - find(callback: Function, target: any): any; + find(callback: ItemIndexEnumerableCallback, target: any): any; findBy(key: string, value?: string): any; - forEach(callback: Function, target?: any): any; + forEach(callback: ItemIndexEnumerableCallback, target?: any): any; getEach(key: string): any[]; indexOf(object: any, startAt: number): number; insertAt(idx: number, object: any): any[]; @@ -1239,7 +1297,7 @@ declare namespace Ember { setObjects(objects: any[]): any[]; shiftObject(): any; slice(beginIndex?: number, endIndex?: number): any[]; - some(callback: Function, target?: any): boolean; + some(callback: ItemIndexEnumerableCallback, target?: any): boolean; toArray(): any[]; uniq(): Enumerable; unshiftObject(object: any): any; @@ -1261,22 +1319,29 @@ declare namespace Ember { addEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; addObject(object: any): any; addObjects(objects: Enumerable): MutableEnumberable; - any(callback: Function, target?: any): boolean; + any(callback: ItemIndexEnumerableCallback, target?: any): boolean; anyBy(key: string, value?: string): boolean; someProperty(key: string, value?: string): boolean; compact(): any[]; contains(obj: any): boolean; - enumerableContentDidChange(start: number, removing: Enumerable | number, adding: Enumerable | number): any; + enumerableContentDidChange( + start: number, + removing: Enumerable | number, + adding: Enumerable | number + ): any; enumerableContentDidChange(removing: Enumerable | number, adding: Enumerable | number): any; - enumerableContentWillChange(removing: Enumerable | number, adding: Enumerable | number): Enumerable; - every(callback: Function, target?: any): boolean; + enumerableContentWillChange( + removing: Enumerable | number, + adding: Enumerable | number + ): Enumerable; + every(callback: ItemIndexEnumerableCallback, target?: any): boolean; everyBy(key: string, value?: string): boolean; everyProperty(key: string, value?: string): boolean; - filter(callback: Function, target: any): any[]; + filter(callback: ItemIndexEnumerableCallback, target: any): any[]; filterBy(key: string, value?: string): any[]; - find(callback: Function, target: any): any; + find(callback: ItemIndexEnumerableCallback, target: any): any; findBy(key: string, value?: string): any; - forEach(callback: Function, target?: any): any; + forEach(callback: ItemIndexEnumerableCallback, target?: any): any; getEach(key: string): any[]; invoke(methodName: string, ...args: any[]): any[]; map: ItemIndexEnumerableCallbackTarget; @@ -1289,7 +1354,7 @@ declare namespace Ember { removeObject(object: any): any; removeObjects(objects: Enumerable): MutableEnumberable; setEach(key: string, value?: any): any; - some(callback: Function, target?: any): boolean; + some(callback: ItemIndexEnumerableCallback, target?: any): boolean; toArray(): any[]; uniq(): Enumerable; without(value: any): Enumerable; @@ -1320,7 +1385,7 @@ declare namespace Ember { static activate(): void; addArrayObserver(target: any, opts?: EnumerableConfigurationOptions): any[]; addEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; - any(callback: Function, target?: any): boolean; + any(callback: ItemIndexEnumerableCallback, target?: any): boolean; anyBy(key: string, value?: string): boolean; arrayContentDidChange(startIdx: number, removeAmt: number, addAmt: number): any[]; arrayContentWillChange(startIdx: number, removeAmt: number, addAmt: number): any[]; @@ -1328,17 +1393,24 @@ declare namespace Ember { clear(): any[]; compact(): any[]; contains(obj: any): boolean; - enumerableContentDidChange(start: number, removing: Enumerable | number, adding: Enumerable | number): any; + enumerableContentDidChange( + start: number, + removing: Enumerable | number, + adding: Enumerable | number + ): any; enumerableContentDidChange(removing: Enumerable | number, adding: Enumerable | number): any; - enumerableContentWillChange(removing: Enumerable | number, adding: Enumerable | number): Enumerable; - every(callback: Function, target?: any): boolean; + enumerableContentWillChange( + removing: Enumerable | number, + adding: Enumerable | number + ): Enumerable; + every(callback: ItemIndexEnumerableCallback, target?: any): boolean; everyBy(key: string, value?: string): boolean; everyProperty(key: string, value?: any): boolean; - filter(callback: Function, target: any): any[]; + filter(callback: ItemIndexEnumerableCallback, target: any): any[]; filterBy(key: string, value?: string): any[]; - find(callback: Function, target: any): any; + find(callback: ItemIndexEnumerableCallback, target: any): any; findBy(key: string, value?: string): any; - forEach(callback: Function, target?: any): any; + forEach(callback: ItemIndexEnumerableCallback, target?: any): any; getEach(key: string): any[]; indexOf(object: any, startAt: number): number; insertAt(idx: number, object: any): any[]; @@ -1364,7 +1436,7 @@ declare namespace Ember { setObjects(objects: any[]): any[]; shiftObject(): any; slice(beginIndex?: number, endIndex?: number): any[]; - some(callback: Function, target?: any): boolean; + some(callback: ItemIndexEnumerableCallback, target?: any): boolean; toArray(): any[]; uniq(): Enumerable; unshiftObject(object: any): any; @@ -1512,99 +1584,7 @@ declare namespace Ember { } // FYI - RSVP source comes from https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/promise.js - namespace RSVP { - type PromiseResolve = (value?: T) => void; - type PromiseReject = (reason?: U) => void; - type PromiseResolverFunction = (resolve: PromiseResolve, reject: PromiseReject) => void; - - interface Thenable { - then(onFulfilled?: (value: T) => V | Thenable, onRejected?: (error: any) => X | Thenable): Thenable; - then(onFulfilled?: (value: T) => V | Thenable, onRejected?: (error: any) => void): Thenable; - } - - class Promise implements Thenable { - /** - Promise objects represent the eventual result of an asynchronous operation. The - primary way of interacting with a promise is through its `then` method, which - registers callbacks to receive either a promise's eventual value or the reason - why the promise cannot be fulfilled. - @class RSVP.Promise - @param {function} resolver - @param {String} label optional string for labeling the promise. - Useful for tooling. - @constructor - */ - constructor(resolver: PromiseResolverFunction, label?: string); - - /** - The primary way of interacting with a promise is through its `then` method, - which registers callbacks to receive either a promise's eventual value or the - reason why the promise cannot be fulfilled. - @method then - @param {Function} onFulfilled - @param {Function} onRejected - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} - */ - then(onFulfilled?: (value: T) => V | Thenable, onRejected?: (error: any) => X | Thenable): Promise; - // tslint:disable-next-line - then(onFulfilled?: (value: T) => V | Thenable, onRejected?: (error: any) => void): Promise; - /** - `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same - as the catch block of a try/catch statement. - - @method catch - @param {Function} onRejection - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} - */ - catch(onRejection: (a: any) => U, label?: string): Promise; - - /** - `finally` will be invoked regardless of the promise's fate just as native - try/catch/finally behaves - - @method finally - @param {Function} callback - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} - */ - finally(callback: (a: T) => V, label?: string): Promise; - - static all(promises: GlobalArray<(Q | Thenable)>): Promise; - static race(promises: GlobalArray>): Promise; - - /** - @method resolve - @param {Any} value value that the returned promise will be resolved with - @param {String} label optional string for identifying the returned promise. - Useful for tooling. - @return {Promise} a promise that will become fulfilled with the given - `value` - */ - static resolve(object?: Q | Thenable): Promise; - - /** - @method cast (Deprecated in favor of resolve - @param {Any} value value that the returned promise will be resolved with - @param {String} label optional string for identifying the returned promise. - Useful for tooling. - @return {Promise} a promise that will become fulfilled with the given - `value` - */ - static cast(object: Q | Thenable, label?: string): Promise; - - /** - `RSVP.Promise.reject` returns a promise rejected with the passed `reason`. - */ - static reject(reason?: any): Promise; - } - - function all(promises: GlobalArray>): Promise; - } + const RSVP: typeof Rsvp; /** The `Ember.Route` class is used to define individual routes. Refer to @@ -1641,7 +1621,7 @@ declare namespace Ember { resolves. Otherwise, non-promise return values are not utilized in any way. */ - afterModel(resolvedModel: any, transition: EmberStates.Transition): RSVP.Promise; + afterModel(resolvedModel: any, transition: EmberStates.Transition): Rsvp.Promise; /** This hook is the first of the route entry validation hooks @@ -1670,7 +1650,7 @@ declare namespace Ember { resolves. Otherwise, non-promise return values are not utilized in any way. */ - beforeModel(transition: EmberStates.Transition): RSVP.Promise; + beforeModel(transition: EmberStates.Transition): Rsvp.Promise; /** The controller associated with this route. @@ -1735,7 +1715,7 @@ declare namespace Ember { @method disconnectOutlet @param {Object|String} options the options hash or outlet name */ - disconnectOutlet(options: DisconnectOutletOptions|string): void; + disconnectOutlet(options: DisconnectOutletOptions | string): void; /** @method findModel @@ -1783,7 +1763,7 @@ declare namespace Ember { the promise resolves, and the resolved value of the promise will be used as the model for this route. */ - model(params: {}, transition: EmberStates.Transition): any|RSVP.Promise; + model(params: {}, transition: EmberStates.Transition): any | Rsvp.Promise; /** Returns the model of a parent (or any ancestor) route @@ -2262,7 +2242,7 @@ declare namespace Ember { class Adapter extends Ember.Object { constructor(); } - class Promise extends Ember.RSVP.Promise { + class Promise extends Rsvp.Promise { constructor(); } function oninjectHelpers(callback: Function): void; @@ -2349,7 +2329,13 @@ declare namespace Ember { actionContext: any; } const ViewUtils: {}; // TODO: define interface - function addListener(obj: any, eventName: string, target: Function | any, method: Function | string, once?: boolean): void; + function addListener( + obj: any, + eventName: string, + target: Function | any, + method: Function | string, + once?: boolean + ): void; const addObserver: ModifyObserver; /** Ember.alias is deprecated. Please use Ember.aliasMethod or Ember.computed.alias instead. @@ -2375,7 +2361,7 @@ declare namespace Ember { equal(dependentKey: string, value: any): ComputedProperty; filter( dependentKey: string, - callback: (item: any, index?: number, array?: any[] ) => boolean + callback: (item: any, index?: number, array?: any[]) => boolean ): ComputedProperty; filterBy(dependentKey: string, propertyKey: string, value: any): ComputedProperty; gt(dependentKey: string, value: number): ComputedProperty; @@ -2392,7 +2378,11 @@ declare namespace Ember { readOnly(dependentString: string): ComputedProperty; }; // ReSharper restore DuplicatingLocalDeclaration - function controllerFor(container: Container, controllerName: string, lookupOptions?: {}): Controller; + function controllerFor( + container: Container, + controllerName: string, + lookupOptions?: {} + ): Controller; function copy(obj: any, deep: boolean): any; /** Creates an instance of the CoreObject class. @@ -2411,7 +2401,11 @@ declare namespace Ember { const empty: typeof deprecateFunc; function endPropertyChanges(): void; function finishChains(obj: any): void; - function generateController(container: Container, controllerName: string, context: any): Controller; + function generateController( + container: Container, + controllerName: string, + context: any + ): Controller; function generateGuid(obj: any, prefix?: string): string; function get(obj: any, keyName: string): any; function getProperties(obj: any, ...args: string[]): object; @@ -2467,7 +2461,12 @@ declare namespace Ember { function propertyIsEnumerable(prop: string): boolean; function propertyWillChange(obj: any, keyName: string): void; function removeChainWatcher(obj: any, keyName: string, node: any): void; - function removeListener(obj: any, eventName: string, target: Function | any, method: Function | string): void; + function removeListener( + obj: any, + eventName: string, + target: Function | any, + method: Function | string + ): void; function removeObserver(obj: any, path: string, target: any, method: Function): any; function required(): Descriptor; function rewatch(obj: any): void; @@ -2502,7 +2501,12 @@ declare namespace Ember { function subscribe(pattern: string, object: any): void; function toLocaleString(): string; function toString(): string; - function tryCatchFinally(tryable: Function, catchable: Function, finalizer: Function, binding?: any): any; + function tryCatchFinally( + tryable: Function, + catchable: Function, + finalizer: Function, + binding?: any + ): any; function tryInvoke(obj: any, methodName: string, args?: any[]): any; function trySet(obj: any, path: string, value: any): void; /** @@ -2531,12 +2535,4 @@ declare namespace Ember { function assign(original: any, ...sources: any[]): any; } -import Em = Ember; - -/** - * External ambient module - to allow "import Ember from 'ember';" to work correctly - */ - -declare module "ember" { - export default Ember; -} +export default Ember; diff --git a/types/rsvp/index.d.ts b/types/rsvp/index.d.ts index a831944a8f..c0a7dc8b07 100644 --- a/types/rsvp/index.d.ts +++ b/types/rsvp/index.d.ts @@ -1,7 +1,11 @@ // Type definitions for RSVP 3.3.3 // Project: https://github.com/tildeio/rsvp.js -// Definitions by: Taylor Brown , Mikael Kohlmyr -// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Definitions by: Taylor Brown +// Mikael Kohlmyr +// Theron Cross +// Chris Krycho +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 // Some of this file was taken from the type definitions for es6-promise https://github.com/borisyankov/DefinitelyTyped/blob/master/es6-promise/es6-promise.d.ts // Credit for that file goes to: François de Campredon @@ -9,230 +13,233 @@ // Some of this file was taken from the type definitions for Q : https://github.com/borisyankov/DefinitelyTyped/blob/master/q/Q.d.ts // Credit for that file goes to: Barrie Nemetchek , Andrew Gaspar , John Reilly -declare module RSVP { +declare namespace RSVP { + type Resolution = (value: T) => U | Thenable; + type Rejection = (error: C) => D | Thenable; - interface Thenable { - then(onFulfilled?:(value:R) => Thenable, onRejected?:(error:any) => Thenable): Thenable; - then(onFulfilled?:(value:R) => Thenable, onRejected?:(error:any) => U): Thenable; - then(onFulfilled?:(value:R) => Thenable, onRejected?:(error:any) => void): Thenable; - then(onFulfilled?:(value:R) => U, onRejected?:(error:any) => Thenable): Thenable; - then(onFulfilled?:(value:R) => U, onRejected?:(error:any) => U): Thenable; - then(onFulfilled?:(value:R) => U, onRejected?:(error:any) => void): Thenable; + interface Thenable { + then(label?: string): Thenable; + then(onFulfillment: Resolution, label?: string): Thenable; + then( + onFulfillment: Resolution, + onRejected: Rejection, + label?: string + ): Thenable; } - interface Deferred { - promise: Promise; + interface Catchable { + catch(label?: string): Catchable; + catch(onRejection: (error: C) => D, label?: string): Catchable; + } + + interface Deferred { + promise: Promise; resolve(value: T): void; - reject(reason: any): void; + reject(reason: C): void; } - class Promise implements Thenable { - /** - * If you call resolve in the body of the callback passed to the constructor, - * your promise is fulfilled with result object passed to resolve. - * If you call reject your promise is rejected with the object passed to resolve. - * For consistency and debugging (eg stack traces), obj should be an instanceof Error. - * Any errors thrown in the constructor callback will be implicitly passed to reject(). - */ - constructor(callback:(resolve:(result?:R) => void, reject:(error:any) => void) => void, label? : string); - - /** - * If you call resolve in the body of the callback passed to the constructor, - * your promise will be fulfilled/rejected with the outcome of thenable passed to resolve. - * If you call reject your promise is rejected with the object passed to resolve. - * For consistency and debugging (eg stack traces), obj should be an instanceof Error. - * Any errors thrown in the constructor callback will be implicitly passed to reject(). - */ - constructor(callback:(resolve:(thenable?:Thenable) => void, reject:(error:any) => void) => void, label? : string); - - /** - * onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. - * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. - * Both callbacks have a single parameter , the fulfillment value or rejection reason. - * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. - * If an error is thrown in the callback, the returned promise rejects with that error. - * - * @param onFulfilled called when/if "promise" resolves - * @param onRejected called when/if "promise" rejects - */ - then(onFulfilled?:(value:R) => Thenable, onRejected?:(error:any) => Thenable):Promise; - - /** - * onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. - * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. - * Both callbacks have a single parameter , the fulfillment value or rejection reason. - * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. - * If an error is thrown in the callback, the returned promise rejects with that error. - * - * @param onFulfilled called when/if "promise" resolves - * @param onRejected called when/if "promise" rejects - */ - then(onFulfilled?:(value:R) => Thenable, onRejected?:(error:any) => U):Promise; - - /** - * onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. - * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. - * Both callbacks have a single parameter , the fulfillment value or rejection reason. - * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. - * If an error is thrown in the callback, the returned promise rejects with that error. - * - * @param onFulfilled called when/if "promise" resolves - * @param onRejected called when/if "promise" rejects - */ - then(onFulfilled?:(value:R) => Thenable, onRejected?:(error:any) => void):Promise; - - /** - * onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. - * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. - * Both callbacks have a single parameter , the fulfillment value or rejection reason. - * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. - * If an error is thrown in the callback, the returned promise rejects with that error. - * - * @param onFulfilled called when/if "promise" resolves - * @param onRejected called when/if "promise" rejects - */ - then(onFulfilled?:(value:R) => U, onRejected?:(error:any) => Thenable):Promise; - - /** - * onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. - * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. - * Both callbacks have a single parameter , the fulfillment value or rejection reason. - * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. - * If an error is thrown in the callback, the returned promise rejects with that error. - * - * @param onFulfilled called when/if "promise" resolves - * @param onRejected called when/if "promise" rejects - */ - then(onFulfilled?:(value:R) => U, onRejected?:(error:any) => U):Promise; - - /** - * onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. - * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. - * Both callbacks have a single parameter , the fulfillment value or rejection reason. - * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. - * If an error is thrown in the callback, the returned promise rejects with that error. - * - * @param onFulfilled called when/if "promise" resolves - * @param onRejected called when/if "promise" rejects - */ - then(onFulfilled?:(value:R) => U, onRejected?:(error:any) => void):Promise; - - /** - * Sugar for promise.then(undefined, onRejected) - * - * @param onRejected called when/if "promise" rejects - */ - catch(onRejected?:(error:any) => Thenable):Promise; - - /** - * Sugar for promise.then(undefined, onRejected) - * - * @param onRejected called when/if "promise" rejects - */ - catch(onRejected?:(error:any) => U):Promise; - - /** - * Sugar for promise.then(undefined, onRejected) - * - * @param onRejected called when/if "promise" rejects - */ - catch(onRejected?:(error:any) => void):Promise; - - finally(finallyCallback: () => any): Promise; - - static all(promises: Thenable[]): Promise; - static all(promises: any[]): Promise; - static race(promises:Promise[]):Promise; - - /** - @method resolve - @param {Any} value value that the returned promise will be resolved with - @param {String} label optional string for identifying the returned promise. - Useful for tooling. - @return {Promise} a promise that will become fulfilled with the given - `value` - */ - static resolve(object: Thenable): Promise; - static resolve(object: T): Promise; - - /** - @method cast (Deprecated in favor of resolve - @param {Any} value value that the returned promise will be resolved with - @param {String} label optional string for identifying the returned promise. - Useful for tooling. - @return {Promise} a promise that will become fulfilled with the given - `value` - */ - static cast(object: Thenable, label? : string): Promise; - static cast(object: T, label? : string): Promise; - - /** - `RSVP.Promise.reject` returns a promise rejected with the passed `reason`. - */ - static reject(reason?: any): Promise; + type PromiseStates = 'fulfilled' | 'rejected' | 'pending'; + interface IPromiseState { + state: PromiseStates; + value: T; + reason: C; } - interface PromiseState { - state: string /* "fulfilled", "rejected", "pending" */; - value?: T; - reason?: any; + class Resolved implements IPromiseState { + state: 'fulfilled'; + value: T; + reason: never; } - interface InstrumentEvent{ - guid:string; // guid of promise. Must be globally unique, not just within the implementation - childGuid:string; // child of child promise (for chained via `then`) - eventName:string; // one of ['created', 'chained', 'fulfilled', 'rejected'] - detail:any; // fulfillment value or rejection reason, if applicable - label:string; // label passed to promise's constructor - timeStamp:number; // milliseconds elapsed since 1 January 1970 00:00:00 UTC up until now + class Rejected implements IPromiseState { + state: 'rejected'; + value: never; + reason: C; } - export function on(eventName : string, callback: (value:any)=>void) : void; - export function on(eventName : "error", errorHandler: (reason:any)=>void): void; - export function on(eventName : "created", listener: (event:InstrumentEvent)=>void): void; - export function on(eventName : "chained", listener: (event:InstrumentEvent)=>void): void; - export function on(eventName : "fulfilled", listener: (event:InstrumentEvent)=>void): void; - export function on(eventName : "rejected", listener: (event:InstrumentEvent)=>void): void; + class Pending implements IPromiseState { + state: 'pending'; + value: never; + reason: never; + } - export function configure(configName : string, value : any): void; - export function configure(configName : "instrument", shouldInstrument : boolean): void; + type PromiseState = Resolved | Rejected | Pending; - /** - * configure('onerror', handler) is deprecated in favor of on('error', handler) - * @param configName - * @param errorHandler - */ - export function configure(configName : "onerror", errorHandler : (reason:any)=>void): void; + type PromiseHash = { [P in keyof T]: Thenable | T[P] }; + + type SettledHash = { [P in keyof T]: PromiseState }; + + interface InstrumentEvent { + guid: string; // guid of promise. Must be globally unique, not just within the implementation + childGuid: string; // child of child promise (for chained via `then`) + eventName: string; // one of ['created', 'chained', 'fulfilled', 'rejected'] + detail: any; // fulfillment value or rejection reason, if applicable + label: string; // label passed to promise's constructor + timeStamp: number; // milliseconds elapsed since 1 January 1970 00:00:00 UTC up until now + } + + interface ObjectWithEventMixins { + on( + eventName: 'created' | 'chained' | 'fulfilled' | 'rejected', + listener: (event: InstrumentEvent) => void + ): void; + on(eventName: 'error', errorHandler: (reason: any) => void): void; + on(eventName: string, callback: (value: any) => void): void; + off(eventName: string, callback?: (value: any) => void): void; + trigger(eventName: string, options?: any, label?: string): void; + } + + class Promise implements Thenable, Catchable { + /** + * If you call resolve in the body of the callback passed to the constructor, + * your promise is fulfilled with result object passed to resolve. + * If you call reject your promise is rejected with the object passed to reject. + * For consistency and debugging (eg stack traces), obj should be an instanceof Error. + * Any errors thrown in the constructor callback will be implicitly passed to reject(). + */ + constructor( + callback: ( + resolve: (result?: T | Thenable) => void, + reject: (error: C | Thenable) => void + ) => void, + label?: string + ); + + /** + * onFulfillment is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. + * Both are optional, if either/both are omitted the next onFulfillment/onRejected in the chain is called. + * Both callbacks have a single parameter , the fulfillment value or rejection reason. + * "then" returns a new promise equivalent to the value you return from onFulfillment/onRejected after being passed through Promise.resolve. + * If an error is thrown in the callback, the returned promise rejects with that error. + * + * @param onFulfillment called when/if "promise" resolves + * @param onRejected called when/if "promise" rejects + * @param label useful for tooling + */ + then( + onFulfillment: Resolution, + onRejected: Rejection, + label?: string + ): Promise; + then(onFulfillment: Resolution, label?: string): Promise; + then(label?: string): Promise; + + /** + * Sugar for promise.then(undefined, onRejected) + */ + catch(label?: string): Promise; + catch(onRejection: Rejection, label?: string): Promise; + + finally(finallyCallback: Function): Promise; + + /** + * `RSVP.Promise.all` accepts an array of promises, and returns a new promise which + * is fulfilled with an array of fulfillment values for the passed promises, or + * rejected with the reason of the first passed promise to be rejected. It casts all + * elements of the passed iterable to promises as it runs this algorithm. + */ + static all(promises: Thenable[], label?: string): Promise; + + /** + * `RSVP.Promise.race` returns a new promise which is settled in the same way as the + * first passed promise to settle. + * + * `RSVP.Promise.race` is deterministic in that only the state of the first + * settled promise matters. For example, even if other promises given to the + * `promises` array argument are resolved, but the first settled promise has + * become rejected before the other promises became fulfilled, the returned + * promise will become rejected. + */ + static race(promises: Promise[]): Promise; + + /** + * Returns a promise that will become resolved with the passed `value` + */ + static resolve(value: T, label?: string): Promise; + + /** + * Deprecated in favor of resolve + */ + static cast(value: T, label?: string): Promise; + + /** + * Returns a promise rejected with the passed `reason`. + */ + static reject(reason: C): Promise; + } + + export namespace EventTarget { + /** `RSVP.EventTarget.mixin` extends an object with EventTarget methods. */ + function mixin(object: object): ObjectWithEventMixins; + + /** Registers a callback to be executed when `eventName` is triggered */ + function on( + eventName: 'created' | 'chained' | 'fulfilled' | 'rejected', + listener: (event: InstrumentEvent) => void + ): void; + function on(eventName: 'error', errorHandler: (reason: any) => void): void; + function on(eventName: string, callback: (value: any) => void): void; + + /** + * You can use `off` to stop firing a particular callback for an event. + * + * If you don't pass a `callback` argument to `off`, ALL callbacks for the + * event will not be executed when the event fires. + */ + function off(eventName: string, callback?: (value: any) => void): void; + + /** + * Use `trigger` to fire custom events. + * + * You can also pass a value as a second argument to `trigger` that will be + * passed as an argument to all event listeners for the event + */ + function trigger(eventName: string, options?: any, label?: string): void; + } + + export function configure( + configName: 'instrument' | 'instrument-with-stack', + shouldInstrument: boolean + ): void; + export function configure(configName: string, value: any): void; /** * Make a promise that fulfills when every item in the array fulfills, and rejects if (and when) any item rejects. * the array passed to all can be a mixture of promise-like objects and other objects. * The fulfillment value is an array (in order) of fulfillment values. The rejection value is the first rejection value. */ - export function all(promises: Thenable[]): Promise; - export function all(promises: any[]): Promise; + export function all(promises: Thenable[]): Promise; + /** - * Make a promise that fulfills when every item in the array fulfills, and rejects if (and when) any item rejects. - * the array passed to all can be a mixture of promise-like objects and other objects. - * The fulfillment value is an array (in order) of fulfillment values. The rejection value is the first rejection value. - * The key difference to the all() function is that both the fulfillment value and the argument to the hash() function - * are object literals. This allows you to simply reference the results directly off the returned object without - * having to remember the initial order like you would with all(). + * `RSVP.hash` is similar to `RSVP.all`, but takes an object instead of an array + * for its `promises` argument. * + * Returns a promise that is fulfilled when all the given promises have been + * fulfilled, or rejected if any of them become rejected. The returned promise + * is fulfilled with a hash that has the same key names as the `promises` object + * argument. If any of the values in the object are not promises, they will + * simply be copied over to the fulfilled object. + * + * If any of the `promises` given to `RSVP.hash` are rejected, the first promise + * that is rejected will be given as the reason to the rejection handler. */ - export function hash(promises: { [key: string]: Thenable }): Promise<{ [key: string]: T }>; - export function hash(promises: { [key: string]: any }): Promise<{ [key: string]: T }>; + export function hash(promises: PromiseHash): Promise; /** - `RSVP.map` is similar to JavaScript's native `map` method, except that it - waits for all promises to become fulfilled before running the `mapFn` on - each item in given to `promises`. `RSVP.map` returns a promise that will - become fulfilled with the result of running `mapFn` on the values the promises - become fulfilled with. + * `RSVP.map` is similar to JavaScript's native `map` method. `mapFn` is eagerly called + * meaning that as soon as any promise resolves its value will be passed to `mapFn`. + * `RSVP.map` returns a promise that will become fulfilled with the result of running + * `mapFn` on the values the promises become fulfilled with. + * + * If any of the `promises` given to `RSVP.map` are rejected, the first promise + * that is rejected will be given as an argument to the returned promise's + * rejection handler. */ - export function map(promises: Thenable[], mapFn : (item:any)=>any, label? : string): Promise; - export function map(promises: any[], mapFn : (item:any)=>any, label? : string): Promise; - + export function map( + promises: Thenable[], + mapFn: (item: T) => U, + label?: string + ): Promise; /** * `RSVP.allSettled` is similar to `RSVP.all`, but instead of implementing @@ -240,8 +247,7 @@ declare module RSVP { * shows you all the results. This is useful if you want to handle multiple * promises' failure states together as a set. */ - export function allSettled(promises: Thenable[]): Promise[]>; - export function allSettled(promises: any[]): Promise[]>; + export function allSettled(promises: Thenable[]): Promise[], C>; /** * `RSVP.hashSettled` is similar to `RSVP.allSettled`, but takes an object @@ -253,40 +259,98 @@ declare module RSVP { * with their states and values/reasons. This is useful if you want to * handle multiple promises' failure states together as a set. */ - export function hashSettled(promises: Thenable[]): Promise[]>; - export function hashSettled(promises: any[]): Promise[]>; + export function hashSettled(promises: PromiseHash): Promise, C>; /** * Make a Promise that fulfills when any item fulfills, and rejects if any item rejects. */ - function race(promises:Promise[]):Promise; + function race(promises: Promise[]): Promise; /** - * `RSVP.denodeify` takes a "node-style" function and returns a function that - * will return an `RSVP.Promise`. You can use `denodeify` in Node.js or the - * browser when you'd prefer to use promises over using callbacks. For example, - * `denodeify` transforms the following: - */ - export function denodeify(nodeFunction: Function, ...args: any[]): (...args: any[]) => Promise; + * `RSVP.denodeify` takes a "node-style" function and returns a function that + * will return an `RSVP.Promise`. You can use `denodeify` in Node.js or the + * browser when you'd prefer to use promises over using callbacks. For example, + * `denodeify` transforms the following: + * + * ``` + * let fs = require('fs'); + * + * fs.readFile('myfile.txt', function(err, data){ + * if (err) return handleError(err); + * handleData(data); + * }); + * ``` + * + * into: + * + * ``` + * let fs = require('fs'); + * let readFile = RSVP.denodeify(fs.readFile); + * + * readFile('myfile.txt').then(handleData, handleError); + * ``` + * + * If the node function has multiple success parameters, then denodeify just + * returns the first one: + * + * ``` + * let request = RSVP.denodeify(require('request')); + * + * request('http://example.com').then(function(res) { + * // ... + * }); + * ``` + * + * However, if you need all success parameters, setting denodeify's second + * parameter to true causes it to return all success parameters as an array: + * + * ``` + * let request = RSVP.denodeify(require('request'), true); + * + * request('http://example.com').then(function(result) { + * // result[0] -> res + * // result[1] -> body + * }); + * ``` + * + * Or if you pass it an array with names it returns the parameters as a hash: + * + * ``` + * let request = RSVP.denodeify(require('request'), ['res', 'body']); + * + * request('http://example.com').then(function(result) { + * // result.res + * // result.body + * }); + * ``` + */ + export function denodeify( + nodeFunction: Function, + options: boolean | string[] + ): (...args: A[]) => Promise; /** - * Favor the Promise Constructor instead (if possible) + * `RSVP.defer` returns an object similar to jQuery's `$.Deferred`. + * `RSVP.defer` should be used when porting over code reliant on `$.Deferred`'s + * interface. New code should use the `RSVP.Promise` constructor instead. * + * The object returned from `RSVP.defer` is a plain object with three properties: + * * promise - an `RSVP.Promise`. + * * reject - a function that causes the `promise` property on this object to become rejected + * * resolve - a function that causes the `promise` property on this object to become fulfilled. */ - export function defer(): Deferred; - + export function defer(label?: string): Deferred; /** - `RSVP.Promise.reject` returns a promise rejected with the passed `reason`. + * `RSVP.Promise.reject` returns a promise rejected with the passed `reason`. */ - export function reject(reason?: any): Promise; + export function reject(reason: C): Promise; /** - `RSVP.Promise.resolve` returns a promise that will become resolved with the - passed `value`. + * `RSVP.Promise.resolve` returns a promise that will become resolved with the + * passed `value`. */ - export function resolve(object: Thenable): Promise; - export function resolve(object: T): Promise; + export function resolve(value: T): Promise; /** * `RSVP.filter` is similar to JavaScript's native `filter` method, except that it @@ -295,25 +359,24 @@ declare module RSVP { * become fulfilled with the result of running `filterFn` on the values the * promises become fulfilled with. */ - export function filter(promises: Thenable[], filterFn:(value:any)=>any): Promise; + export function filter( + promises: Thenable[], + filterFn: (value: T) => boolean | Promise + ): Promise; /** - `RSVP.rethrow` will rethrow an error on the next turn of the JavaScript event - loop in order to aid debugging. - - Promises A+ specifies that any exceptions that occur with a promise must be - caught by the promises implementation and bubbled to the last handler. For - this reason, it is recommended that you always specify a second rejection - handler function to `then`. However, `RSVP.rethrow` will throw the exception - outside of the promise, so it bubbles up to your console if in the browser, - or domain/cause uncaught exception in Node. `rethrow` will also throw the - error again so the error can be handled by the promise per the spec. + * `RSVP.rethrow` will rethrow an error on the next turn of the JavaScript event + * loop in order to aid debugging. + * + * Promises A+ specifies that any exceptions that occur with a promise must be + * caught by the promises implementation and bubbled to the last handler. For + * this reason, it is recommended that you always specify a second rejection + * handler function to `then`. However, `RSVP.rethrow` will throw the exception + * outside of the promise, so it bubbles up to your console if in the browser, + * or domain/cause uncaught exception in Node. `rethrow` will also throw the + * error again so the error can be handled by the promise per the spec. */ - export function rethrow(reason : any):void; - + export function rethrow(reason: C): void; } - -declare module "rsvp" { - export = RSVP; -} +export default RSVP; diff --git a/types/rsvp/rsvp-tests.ts b/types/rsvp/rsvp-tests.ts index 50770ba8b6..519947dcc7 100644 --- a/types/rsvp/rsvp-tests.ts +++ b/types/rsvp/rsvp-tests.ts @@ -1,4 +1,83 @@ -import rsvp = require("rsvp"); +import RSVP from 'rsvp'; -var promise = new rsvp.Promise(function(resolve:any, rejector:any){ +let promise1: RSVP.Promise = RSVP.Promise.resolve(1); +let promise1a: RSVP.Promise = RSVP.resolve(1); + +let promise2: RSVP.Promise = RSVP.Promise.resolve(2); + +let promise3: RSVP.Promise = RSVP.Promise.reject(new Error('3')); +let promise3a: RSVP.Promise = RSVP.reject(new Error('3')); + +let promiseArray = [promise1, promise2, promise3]; + +let promiseHash = { + promiseA: promise1, + promiseB: promise2, + promiseC: promise3, + notAPromise: 4, +}; + +RSVP.Promise.all(promiseArray).then(arr => {}, err => {}); +RSVP.all(promiseArray).then(arr => {}, err => {}); + +RSVP.Promise.race(promiseArray).then(arr => {}, err => {}); +RSVP.race(promiseArray).then(arr => {}, err => {}); + +RSVP.allSettled(promiseArray).then(arr => {}, err => {}); + +let deferred = RSVP.defer(); +deferred.resolve('Success'); +deferred.promise.then(value => {}); + +let filterFn = (item: number) => { + return item > 1; +}; +RSVP.filter(promiseArray, filterFn).then(result => {}); + +RSVP.hashSettled(promiseHash).then(hash => { + return ( + hash.promiseA.state === 'fulfilled' && + hash.promiseB.value === 2 && + hash.promiseC.reason === '3' && + hash.notAPromise.state === 'fulfilled' + ); }); + +RSVP.hash(promiseHash).then( + values => { + return ( + values.promiseA < 0 && + values.promiseB === 4 && + values.promiseC === 12 && + values.notAPromise > 0 + ); + }, + err => {} +); + +let mapFn = function(item: number) { + return item + 1; +}; +RSVP.map(promiseArray, mapFn).then(function(result) {}); + +let promise = new Promise(function(resolve, reject) { + resolve(); + reject(); +}); +promise.then(value => {}, reason => {}); + +function throws() { + throw new Error('Whoops!'); +} +let throwingPromise = new RSVP.Promise(function(resolve, reject) { + throws(); +}); +throwingPromise.catch(RSVP.rethrow).then(value => {}, reason => {}); + +let someObject = {}; +RSVP.EventTarget.mixin(someObject); +RSVP.EventTarget.on('fulfilled', someString => { + return someString; +}); +RSVP.EventTarget.trigger('fulfilled', 'woohoo'); +RSVP.EventTarget.off('fulfilled');