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

  • Compare New GitHub Copilot Free Plan for Visual Studio/VS Code to Paid Plans

    The free plan restricts the number of completions, chat requests and access to AI models, being suitable for occasional users and small projects.

  • Diving Deep into .NET MAUI

    Ever since someone figured out that fiddling bits results in source code, developers have sought one codebase for all types of apps on all platforms, with Microsoft's latest attempt to further that effort being .NET MAUI.

  • Copilot AI Boosts Abound in New VS Code v1.96

    Microsoft improved on its new "Copilot Edit" functionality in the latest release of Visual Studio Code, v1.96, its open-source based code editor that has become the most popular in the world according to many surveys.

  • AdaBoost Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the AdaBoost.R2 algorithm for regression problems (where the goal is to predict a single numeric value). The implementation follows the original source research paper closely, so you can use it as a guide for customization for specific scenarios.

  • Versioning and Documenting ASP.NET Core Services

    Building an API with ASP.NET Core is only half the job. If your API is going to live more than one release cycle, you're going to need to version it. If you have other people building clients for it, you're going to need to document it.

Subscribe on YouTube