image credit: Maragda Farràs

TypeScript vs. C#: 'as' keyword

last updated: Nov 11th, 2017

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

Level up Your React + Redux + TypeScript

with articles, tutorials, sample code, and Q&A.