If you are looking to store the outcome of narrowing down in isValidName
for future reference without having to recompute it, you can define a utility function as follows:
/**
* @param a The precomputed result
* @param _b The variable to be narrowed down
* @template T The type to which `_b` will be narrowed down to when `a` is true
*/
function typeCheck<T>(a: boolean, _b: any): _b is T {
return a
}
Usage example:
if (typeCheck<string>(isValidName, myName)) {
console.log(helloWorld(myName)); // string here
} else {
console.log(myName) // null here
}
Playground
This method can prove useful when dealing with lengthy expressions like:
if (
isLoneAvailableCapacity(feed) &&
(isAvailableCapacitySubbeamPath(link) || isAvailableCapacityConnectivityLegPath(link)) &&
toAvailableCapacityKey(feed.availableCapacity) === link.availableCapacityKey
) {
// do something
}
// snip....
// some more code
if (
isLoneAvailableCapacity(feed) &&
(isAvailableCapacitySubbeamPath(link) || isAvailableCapacityConnectivityLegPath(link)) &&
toAvailableCapacityKey(feed.availableCapacity) === link.availableCapacityKey
) {
// do something else
}
Instead, you can simplify it by using:
const isValidFeed = isLoneAvailableCapacity(feed) &&
(isAvailableCapacitySubbeamPath(link) || isAvailableCapacityConnectivityLegPath(link)) &&
toAvailableCapacityKey(feed.availableCapacity) === link.availableCapacityKey
if(typeCheck<Feed>(isValidFeed, feed)) {
// do something
}
// snip....
// some more code
if(typeCheck<Feed>(isValidFeed, feed)) {
// do something else
}