Closed
Description
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)