-
Notifications
You must be signed in to change notification settings - Fork 124
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
.filter()
can't handle union of arrays
#168
Comments
This was fixed upstream in TS I think! |
Unfortunately, this still occurs with the latest TypeScript 5.3.3. |
Looks fixed in this playground: |
@mattpocock you forgot to add Update:Looking at the code for /// <reference path="utils.d.ts" />
interface Array<T> {
+ filter(predicate: (item: T, index: number, array: T[]) => boolean, thisArg?: any): TSReset.NonFalsy<T>[];
- filter(predicate: BooleanConstructor, thisArg?: any): TSReset.NonFalsy<T>[];
}
interface ReadonlyArray<T> {
+ filter(predicate: (item: T, index: number, array: T[]) => boolean, thisArg?: any): TSReset.NonFalsy<T>[];
- filter(predicate: BooleanConstructor, thisArg?: any): TSReset.NonFalsy<T>[];
} Here is an updated example: |
Hmm. Looks like the above solution breaks type predicate filters. // With the interface
const list1 = ["0", 0, false];
const list2 = list1.filter((v): v is number => typeof v === "number");
// ^? (string | number | true)[]
console.log(list2); // 0
// Without the interface
const list1 = ["0", 0, false];
const list2 = list1.filter((v): v is number => typeof v === "number");
// ^? number[]
console.log(list2); // 0 |
This is actually a pretty fundamental problem with the ts-reset approach that I think will be hard to fix. microsoft/TypeScript#53489 added special logic for calling methods on I think adding an overload to |
interface Array<T> {
filter<S extends T>(
predicate: (value: T, index: number, array: readonly T[]) => value is S,
thisArg?: unknown,
): S[]; // duplicated from DOM types
filter<P extends (value: T, index: number, array: T[]) => unknown>(
predicate: P,
thisArg?: unknown,
): (P extends BooleanConstructor ? NonFalsy<T> : T)[];
} I've been using this solution without problems for a while, although I haven't looked much into why it works. Interstingly, the overloads have to be in this order for it to work. The |
Example:
In this example both
ClientA
andClientB
has a common fieldisAdmin
but.filter()
can't handle this union.Removing
ts-reset
fixed the error.Also changing the type to
(ClientA | ClientB)[]
fixed the error, but it can be inconvenient in some cases because of a forced type cast.The text was updated successfully, but these errors were encountered: