Skip to content

allow storing results of narrowing in booleans for further narrowing #24865

Closed
@zpdDG4gta8XKpMCd

Description

@zpdDG4gta8XKpMCd

Search Terms

https://github.com/Microsoft/TypeScript/search?q=type+guards+constants+narrowing&type=Issues

Suggestion

There is no way to use a saved result of a type guard evaluation for narrowing. Allow narrowing by

  • storing assertions (booleans) of narrowing into constants
  • impose narrowing based on the values carried by those constants

Use Cases

  • reuse for narrowing evaluations, in case there are two places that narrow using the same guard on the same value
  • declutter "if" expressions
  • give names to narrowing facts for better readability

Examples

// now
            if (
                isLoneAvailableCapacity(feed) &&
                (isAvailableCapacitySubbeamPath(link) || isAvailableCapacityConnectivityLegPath(link)) &&
                toAvailableCapacityKey(feed.availableCapacity) === link.availableCapacityKey
            ) {


// could be
            const isAvailableCapacityPairdWithPath = isLoneAvailableCapacity(feed) &&
                (isAvailableCapacitySubbeamPath(link) || isAvailableCapacityConnectivityLegPath(link)) &&
                toAvailableCapacityKey(feed.availableCapacity) === link.availableCapacityKey

            if (isAvailableCapacityPairdWithPath) {
            }

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. new expression-level syntax)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs ProposalThis issue needs a plan that clarifies the finer details of how it could be implemented.SuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions