image credit: Maragda Farràs

TypeScript vs. C#: 'as' keyword


As a C# developer you're accustomed to working with interfaces, classes, and subclasses.

C# has the 'as' keyword to cast an object from one type to another. For example:

private void SomeEventHandler(object sender, EventArgs e){  var someThing = sender as SomeClass;  // ...}

Furthermore, in C#, the as type-cast expression returns null if the object and target type are incompatible.

using System;public class Program{  public interface IThing {}  public class A : IThing {}  public class B : IThing {}  public static void Main()  {    IThing thing = new A();    var a = thing as A;    var b = thing as B;    Console.WriteLine(a == null); // False    Console.WriteLine(b == null); // True  }}


TypeScript also has an as keyword -- but beware that it behaves differently than in C#!

When you work with TypeScript, the as keyword is only telling the type checker to pretend something has a different type. You can think of the type annotations as a separate, meta layer on top of the actual code.

All the type-checking information is discarded when the TypeScript is compiled into JavaScript.

So if you were accustomed to C# and had the following TypeScript code, you might be surprised to find that b is not null.

type IThing = {};class A implements IThing {}class B implements IThing {}const thing: IThing = new A();const a = thing as A;const b = thing as B;console.log(a == null); // falseconsole.log(b == null); // false !!!

The TypeScript compiler produces this ES5 JavaScript:

var A = (function () {    function A() {    }    return A;}());var B = (function () {    function B() {    }    return B;}());var thing = new A();var a = thing;var b = thing;console.log(a == null); // falseconsole.log(b == null); // false !!!


Remember, as is only for telling the type checker to treat something as a different type.

More in the TypeScript vs. C# Series

The Wild, Wild Web is a scary and dangerous place where JavaScript reigns supreme. But there's a new sheriff in town... TypeScript.

Sign up on my email list to learn about the new Law of the Land (and related web development topics).