From this tutorial: A user-defined type guard function is a function that returns "arg is aType". For example:
function isCustomer(partner: any): partner is Customer {
return partner instanceof Customer;
}
function signContract(partner: BusinessPartner): string {
let message: string;
if (isCustomer(partner)) {
message = partner.isCreditAllowed() ? 'Sign a new contract with the customer' : 'Credit issue';
} else {
message = partner.isInShortList() ? 'Sign a new contract with the supplier' : 'Need to evaluate further';
}
return message;
}
Why is the return type of 'partner is Customer' advantageous over simply returning a boolean?
CodePudding user response:
The line
message = partner.isCreditAllowed() ? 'Sign a new contract with the customer' : 'Credit issue';
is the point of the tutorial.
Normally you would have to cast partner
to type Customer
before calling isCreditAllowed
. But because you have a Type Guard on the isCustomer
return type, TypeScript can dispense with the need for a cast.
Expressions like typeof A === B
carry these guards implicitly. But by replacing that condition with a function call, you have to "put that information back" into the expression by making the claim in the return type of isCustomer
. boolean
alone would not be enough for the interpreter.