Skip to content

Accept de-structured elements in type predicates #41173

Description

@rraziel

Search Terms

  • type predicate
  • reference binding pattern
  • type predicate cannot reference
  • destructured

Suggestion

The possibility to use destructured parameters in type predicates.

Use Cases

Destructuring is heavily used in functional/reactive programming, notably with rxjs where various contextual properties tend to be passed between each operator.

Having the ability to succinctly test for types would make the code more readable, e.g.:

typeExample={a: number;b: string|undefined;};constexample: Example={a: 42,b: 'hello';};of(example).pipe(guard(({ b }): b is string=>b!==undefined,'b cannot be undefined'),tap({ b })=>{/*bisnowastringratherthanastring|undefined}));

Right now the alternative is

of(example).pipe(guard((x): x is Omit<typeofx,'b'>&{b: string}=>x.b!==undefined,'b cannot be undefined'),tap({ b })=>{/*bisnowastringratherthanastring|undefined}));

Or, without a predicate

of(example).pipe(map(x=>{if(x.b===undefined){thrownewError();}returnx;}),tap({ b })=>{/*bisnowastringratherthanastring|undefined}));

Examples

functionassertSomething({ property }: T): property is AssertionHere{returntrue;}

This would roughly translate to something like:

functionassertSomething(obj: T): obj is Omit<T,'property'>&{property: AssertionHere}{returntrue;}

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