The Practical Client

Type Flexibility with Conditional Types

There's a dialogue that goes on between TypeScript and JavaScript because, essentially, JavaScript isn't typed and TypeScript is. As Douglas Crockford points out in "JavaScript: The Good Parts," the lack of data typing in JavaScript shouldn't be regarded as a mistake but, instead, as one of the language's features. With that view, by adding data typing, TypeScript takes some of the power of JavaScript away.

I'm not complaining about that loss. My background is in data-typed languages and I value the IntelliSense support and compile-time checking that TypeScript gives me. However, I've done enough JavaScript programming to also value the advantages that developing without types gives me.

To provide support for programming with and without data typing, many parts of TypeScript provide a flexible approach to selecting types. Many features of TypeScript aren't so much about "setting the data type" as "dynamically controlling data typing" (TypeScript's intersection and union types leap to mind as examples). The latest example of this dynamic approach to data typing appears in TypeScript 2.8 with conditional typing.

Redefining Types
Conditional typing allows you to define a type that varies depending on what kind of object is being referenced by the type. These objects don't need to have anything in common, other than the ability to work with the code that uses the conditional type. The objects don't need, for example, to share a common ancestor in their hierarchy chain or implement a common interface.

As an example, take a method like PayInvoice. My company might receive invoices from a variety of "external entities": vendors who sell us raw materials, service providers like the one that cleans our offices, or business partners who have a claim on us through some joint activity. To support the various types of external entities my company works with, I would have different classes. I would, for example, distinguish between vendors, providers and partners:

class vendor {...}
class provider {...}
class partner {...}

Each of these would have its own Pay method. Here's the vendor class as an example:

class vendor 
{
  Pay(amount: number): number {
    let amountDue: number;
    //...business logic...
    return amountDue;
  }
}

While all our invoices look alike, I want to treat the payee for each invoice very differently. To support that, rather than work with vendors and partners in my PayInvoice method, I prefer to work with different classes of payees: those I want to pay immediately, those I want to pay on the bill's due date, and those I want to put off paying for as long as I can. I'll call those three classes of payees payeeImmediate, payeeStandard and payeeLater:

class payeeImmediate {...}
class payeeLater {...}
class payeeStandard {...}

I could work out some inheritance hierarchy or interface implementation to handle the mapping between external entities and payees ... or I could use conditional typing.

Defining a Flexible Type
To implement conditional typing, outside of any class, I define a new datatype using TypeScript's type keyword. The actual datatype for this type isn't fixed. Instead, the datatype varies depending on the output of an immediate if. Immediate ifs are in the format:

<test>? true result: false result 

In a conditional type, the immediate if checks the type of the object being passed and, based on that object's type, specifies the type to be used for my new datatype.

This type declaration, for example, converts my vendors, providers and partners into payeeImmediate and payeeLater types (and treats everyone else as payeeStandard):

type payeeType<T> = T extends vendor ? payeeImmediate :
                    T extends partner ? payeeLater :
                    T extends provider ? payeeImmediate :
                    payeeStandard;

I can now set the type of a payeeType variable indirectly with code like this:

let vend: vendor;
vend = new vendor("A123");

let payee: payeeType;
payee = vend;

In this case, the type of the payee variable will be payeeImmediate because of the conditionals that I used when defining payeeType to treat vendors as payeeImmediate.

Now I can define the signature for the PayInvoice method in my InvoiceManagement class to accept an external entity datatype and use that to set the correct payee datatype:

class InvoiceManagement 
{
  PayInvoice<T>(bill: invoice, payee: payeeType<T>): number
  {

To call this method, I would use code like this:

let im: InvoiceManagement;
im = new InvoiceManagement();

let inv: invoice;
inv = new Invoice("001023");

let vend: vendor;
vend = new vendor("A123");
im.PayInvoice<vendor>(inv, vend);

Effectively, I've transferred and centralized the conversion of external entities into payee types by moving it out of my business logic and into my conditional datatype. Now it's just a matter of putting the right code in each of my external entities.

About the Author

Peter Vogel is a system architect and principal in PH&V Information Services. PH&V provides full-stack consulting from UX design through object modeling to database design. Peter tweets about his VSM columns with the hashtag #vogelarticles. His blog posts on user experience design can be found at http://blog.learningtree.com/tag/ui/.

comments powered by Disqus

Featured

Subscribe on YouTube