Closed
Description
Consider the following from here:
const asAndBs = [new A(), new B(), new A(), new B()];
const allAs = asAndBs.filter(v => v instanceof A);
The type of allAs
is (A | B)[]
where it would be more accurately typed as A[]
. If a type-guard was used,
function isA(v: any): v is A {
return v instanceof A;
}
const allAs = asAndBs.filter(isA);
then the type would be A[]
as expected.
Getting the correct type from filter
requires using the verbose form filter(isA)
instead of the more terse form filter(v => v instanceof A)
.
Suggestion
Infer a guard from lambdas that imply a type narrowing if used in an if
statement.
For example,
const a = (v: any) => v instanceof Class;
would infer a
to be of type (v: any) => v is Class
.
const b = (v: any) => typeof v === 'string'
would infer b
to be type (v: any) => v is string
;
This would allow useful typing of:
const loweredStrings = someArray.filter(v => typeof v === 'string').map(v => v.toLower());