The Practical Client

Even Better Data Typing with TypeScript 1.4

In TypeScript 1.4, you get type-safe support even when you may be working with multiple types, better type checking when inferring types and aliases for type definitions.

TypeScript continues to gain ground (NativeScript, the new cross-platform development tool from Telerik, is written in TypeScript, for example). Supporting that growth, TypeScript 1.4 is coming and it's got a lot of cool stuff in it. Not surprisingly, much of that cool stuff (and the part I'm most interested in) extends TypeScript's primary feature: data typing. Here are three new data type-related features in TypeScript 1.4.

Supporting Flexible Datatyping
In JavaScript it's not unusual to have functions that return or accept several different data types. It's not unusual, for example, to have a single parameter to a function that accepts either a number or a string ... but not anything else; the function might also return a number or a string (probably based on the datatype of the parameter passed to it).

TypeScript 1.4 includes union types to support this kind of activity in a type-safe way. For example, I can specify that my sample parameter can either be a number or a string by joining the two data types together with the pipe | in the parameters declaration. If I attempt to pass some other datatype to the parameter (a Boolean, for example), TypeScript will spot my error.

This example defines a function that accepts a parameter (called val), which can either be a number or a string; the function also returns either a number or a string:

function flexibleFunction(val: number | string): number | string
{
  val.toString();
}

Calling my method in either of the following examples will give me a compile time error. In the first case because I'm not passing a number or a string, and the second case because I'm putting the result in a variable that is neither a number or a string:

var res: Date;
res = flexibleFunction(true);
res = flexibleFunction(4);

Any of these calls, on the other hand, will work:

var res2: string;
var res3: number;
var res2 = flexibleFunction("hello");
var res3 = flexibleFunction(32);
var res3 = flexibleFunction("hello");
var res2 = flexibleFunction(32);

Picking the Right Type
Within the function, TypeScript will also prevent me from doing anything with my val parameter that isn't supported by both the number or string data types. That means that about the only thing I can do with my val parameter inside flexibleFunction is call its toString method because that's the only method common to both data types.

However, inside my function I can check for the data type of the actual value that's passed at runtime. This check also sets up a type guard that sets the data type for the val within the type guard.

This example checks to see whether val is a number and, if it is, lets me do some math with val within the test:

function flexibleFunction(val: number | string): number | string
{
  if (typeof val === "number") {
    val = val + 4;
  }
  return val.toString();
}

You're not restricted to using type unions in function declarations: You can use a type union anywhere you can use a type. This code declares the variable myVal as being either a Boolean or a string:

var myval: boolean | string;

This example uses a union type to declare an Array called myArray that can hold strings or numbers:

var myArray: Array<number | string>;

Type Aliases
TypeScript 1.4 also lets you define aliases for data types. If, for example, I wanted to use my "number and string" array in several places I could ensure consistency in my declarations (and save myself some typing) by using the type keyword to assign an alias to my array type.

This example establishes the alias myFlexibleArrayType for my number and string array:

type myFlexibleArrayType = Array<boolean | string>;

This example now declares two variables using my alias:

var firstArray: myFlexibleArrayType;
var secondArray: myArrayType;

Type aliases must be declared outside of any function.

Better Type Inference for Generics
TypeScript 1.4 also does a better job at inferring data types, especially with generics. Here's a version of my flexibleFunction that figures out the data type of its parameter (and the function's return value) at runtime:

function flexibleFunction<T>val1: T, val2: T): T
{
  if (val1 === val2) {
    return val1 ;
  }
  return val1;
}

You can call flexibleFunction explicitly specifying the data type with code like this that specifies that T is a string:

flexibleFunction<string>(true, "hello");

If you do use this code, TypeScript will give you a compile time error for the first parameter in my example (the true parameter) because it's a Boolean and not a string. However, TypeScript will also let you call flexibleFunction without explicitly specifying the datatype for T, like this:

flexibleFunction(true, "hello");

Without an explicit declaration for T, TypeScript infers the datatype for T from the parameters being passed to the function. You might assume that TypeScript will give you an error in this case also because TypeScript will notice that there's no data type that it could infer for T that will work for both parameters ... but you would be wrong: Prior to TypeScript 1.4, you wouldn't get a compile time error. Because there's virtually no shared functionality between Booleans and strings, the odds are good that flexibleFunction will do something you won't like.

With TypeScript 1.4, however, even when the data type for T is inferred, TypeScript will spot the problem with the two incompatible data types being passed to flexibleFunction and refuse to compile your code. This is a good thing.

There's more in TypeScript 1.4 than I've sketched out here (there's an ECMAScript 6 compiler option that lets you include functionality in the next version of JavaScript, for example). But what makes TypeScript special is its support for data typing so, as far as I'm concerned, these are the changes that matter.

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