Skip to content

Infer arrow function type guard type for specific simple cases #38390

Closed
@iliazeus

Description

@iliazeus

Search Terms

arrow function type guard

Suggestion

Specific simple cases of arrow functions of a single argument should be considered type guards:

const f1 = x => x typeof "string"; // immediately returns a typeof expression with a literal rhs
const f2 = x => x instanceof Foo; // immediately returns an instanceof expression
const f3 = x => x === "foo"; // immediately returns a strict (non-)equality comparison with a literal
const f4 = x => x == null; // immediately returns a non-strict (non-)equality comparison with a null literal
const f5 = x => isFoo(x); // immediately returns another type guard

There are more general requests like #16069, but I beleive this one should be easier to implement, and it still covers a lot of use cases.

Use Cases

filter with heterogenous arrrays:

// currently: (string | number)[]
// would be: string[]
const a = [1, "foo", 2, "bar"].filter(x => x instanceof "string");

Specifically, filtering out null or undefined elements:

// f: (x: string) => Promise<string | undefined>
const a = await Promise.all(["foo", "bar"].map(f));
const b = a.filter(x => x !== undefined);

Limiting the number of arguments of a more complex type guard:

// isFoo: (x: any, strict?: boolean) => x is Foo
const b1 = a.filter(x => isFoo(x));
const b2 = a.filter(x => isFoo(x, true));

// compare:
const b3 = a.filter(isFoo); // No overload matches this call.

Examples

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions