0
votes

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?

1
It is simply returning a boolean. The difference is that a type guard tells TS to treat that boolean as the argument being a given type or not. Otherwise TS wouldn't guess that a random boolean result has such an implication.tsplay.dev/NDyjjm - VLAZ
Thanks for the clarification. The difference is clear now. I am discovering all sorts of new syntax with Typescript :) - atlantis

1 Answers

1
votes

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.