Type Assertion in Typescript

Typescript’s type assertion features help us to override type inference and indicate a specific type to a variable.

Type assertion may not be the most common of the features you employ, but it is invaluable when you are migrating from Javascript. Or, when you have to interact with Javascript libraries or data from external systems in your Typescript code.

Take note of one important thing though - since all Typescript code is compiled to Javascript, any and all assertion is applied at compile time. There is no runtime type assertion.

So, how do you type assert anything?

Type assertion for simple variables

Consider this very simple example -

const one: any = 1;

In the normal course of time, you end up treating one as a number.

const oneOne = one + 1;
console.log("oneOne: ", oneOne);
// 2

But, what if you want to promote one to a string? This is where assertion plays a part - you can tell Typescript to treat one as a string rather than infer it as a number.

const realOne: string = <string>one;
console.log("realOne: ", realOne);
// 1

realOne is a string representation of the any typed one. It can lend itself well to string operations as expected.

console.log(realOne + "two");
// 1two

You could also do the same assertion using an alternate syntax. Use one as instead of <> syntax.

const one: any = 1;
const realOne: string = one as string;
console.log(realOne + "two");
// 1two

Type assertion in objects

Let’s take a look at a recently used example -

const planet = {};
planet.name = "earth";
// error TS2339: Property 'name' does not exist on type '{}'.

As seen in another post planet is treated as a variable with type {} and therefore, planet.name will throw an error.

We can solve this problem by manually inferring the type.

interface iPlanet {
  name: string;
  position: number;

const planet = <iPlanet>{};
planet.name = "earth";

// { name: 'earth' }
comments powered by Disqus