Skip to content

Commit b2327f4

Browse files
JeanMechedylhunn
authored andcommitted
feat(core): Allow typeguards on QueryList.filter (#48042)
To match the behaviour of Array.filter, typeguards can now be used on QueryList.filter to narrow the return type. Fixes #38446 BREAKING CHANGE: QueryList.filter now supports type guard functions, which will result in type narrowing. Previously if you used type guard functions, it resulted in no changes to the return type. Now the type would be narrowed, which might require updates to the application code that relied on the old behavior. PR Close #48042
1 parent 6ca1a53 commit b2327f4

File tree

3 files changed

+12
-1
lines changed

3 files changed

+12
-1
lines changed

goldens/public-api/core/index.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1199,7 +1199,9 @@ export class QueryList<T> implements Iterable<T> {
11991199
destroy(): void;
12001200
// (undocumented)
12011201
readonly dirty = true;
1202-
filter(fn: (item: T, index: number, array: T[]) => boolean): T[];
1202+
filter<S extends T>(predicate: (value: T, index: number, array: readonly T[]) => value is S): S[];
1203+
// (undocumented)
1204+
filter(predicate: (value: T, index: number, array: readonly T[]) => unknown): T[];
12031205
find(fn: (item: T, index: number, array: T[]) => boolean): T | undefined;
12041206
// (undocumented)
12051207
readonly first: T;

packages/core/src/linker/query_list.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,8 @@ export class QueryList<T> implements Iterable<T> {
9292
* See
9393
* [Array.filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)
9494
*/
95+
filter<S extends T>(predicate: (value: T, index: number, array: readonly T[]) => value is S): S[];
96+
filter(predicate: (value: T, index: number, array: readonly T[]) => unknown): T[];
9597
filter(fn: (item: T, index: number, array: T[]) => boolean): T[] {
9698
return this._results.filter(fn);
9799
}

packages/core/test/linker/query_list_spec.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,13 @@ import {fakeAsync, tick} from '@angular/core/testing';
139139
expect(queryList.some(item => item === 'four')).toEqual(false);
140140
});
141141

142+
it('should support guards on filter', () => {
143+
const qList = new QueryList<'foo'|'bar'>();
144+
qList.reset(['foo']);
145+
const foos: Array<'foo'> = queryList.filter((item): item is 'foo' => item === 'foo');
146+
expect(qList.length).toEqual(1);
147+
});
148+
142149
it('should be iterable', () => {
143150
const data = ['one', 'two', 'three'];
144151
queryList.reset([...data]);

0 commit comments

Comments
 (0)