From 628cbd69e1213d8b3f83950e2034e790b37d206a Mon Sep 17 00:00:00 2001 From: Georgii Dolzhykov Date: Thu, 8 Feb 2018 20:50:26 +0200 Subject: [PATCH] AngularJS: improve types for `foreach` (support for array-likes) --- types/angular/angular-tests.ts | 18 ++++++++++++++++++ types/angular/index.d.ts | 6 +++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/types/angular/angular-tests.ts b/types/angular/angular-tests.ts index 0b05400f6d..ca9d2c7568 100644 --- a/types/angular/angular-tests.ts +++ b/types/angular/angular-tests.ts @@ -710,6 +710,24 @@ function test_angular_forEach() { this.push(`${key}: ${value}`); }, log); // expect(log).toEqual(['name: misko', 'gender: male']); + // $ExpectType NodeListOf + angular.forEach(document.getElementsByTagName('img'), (value, key, obj) => { + value; // $ExpectType HTMLImageElement + key; // $ExpectType number + obj; // $ExpectType NodeListOf + }); + // $ExpectType number[] + angular.forEach([1, 2, 3], (value, key, obj) => { + value; // $ExpectType number + key; // $ExpectType number + obj; // $ExpectType number[] + }); + // $ExpectType string + angular.forEach('123', (value, key, obj) => { + value; // $ExpectType string + key; // $ExpectType number + obj; // $ExpectType string + }); } // angular.element() tests diff --git a/types/angular/index.d.ts b/types/angular/index.d.ts index 32a5c74b52..4c896eb430 100644 --- a/types/angular/index.d.ts +++ b/types/angular/index.d.ts @@ -100,7 +100,11 @@ declare namespace angular { * @param iterator Iterator function. * @param context Object to become context (this) for the iterator function. */ - forEach(obj: T[], iterator: (value: T, key: number, obj: T[]) => void, context?: any): T[]; + forEach = T[]>( + obj: U, + iterator: (value: U[number], key: number, obj: U) => void, + context?: any + ): U; /** * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. *