Skip to content
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

Array.filter should take type guards into account #10021

Closed
maiermic opened this issue Jul 29, 2016 · 2 comments
Closed

Array.filter should take type guards into account #10021

maiermic opened this issue Jul 29, 2016 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@maiermic
Copy link

A common use case of generic collections is filtering elements of a certain subtype.

let c: Array<number | string>

function isString(value: number | string): value is string {
  return typeof value === 'string';
}

let numbers: Array<number> = c.filter(isString) // ERROR: Type '(number | string)[]' is not assignable to type 'number[]'.
let strings: Array<string> = c.filter(isString) // ERROR: Type '(number | string)[]' is not assignable to type 'string[]'.
let mixed: Array<number | string> = c.filter(isString) // OK

Everything works as expected, but the error in the type-safe assignment to strings can be prevented by an improved type signature of Array that takes the type guard of isString into account:

interface Array<T> {
  filter<S extends T>(callbackfn: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[];
}

let numbers: Array<number> = c.filter(isString) // ERROR: Type 'string[]' is not assignable to type 'Array<number>'.
let strings: Array<string> = c.filter(isString) // OK
let mixed: Array<number | string> = c.filter(isString) // OK: Type 'Array<string>' is assignable to type 'Array<number | string>'.

That's great. Everything works as before (with better error messages) and the error in the assignment to strings is prevented. If a callbackfn without a type guard is passed, the old signature of filter matches:

filter(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): T[];

Consequently, we need both signatures.

@yortus
Copy link
Contributor

yortus commented Jul 29, 2016

Duplicate of #7657?

@maiermic
Copy link
Author

@yortus Yes, I have overseen that.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Jul 29, 2016
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants