This page looks best with JavaScript enabled

Type Assertion in Typescript

 ·   ·  ☕ 2 min read

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 -

1
const one: any = 1;

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

1
2
3
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.

1
2
3
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.

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

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

1
2
3
4
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 -

1
2
3
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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
interface iPlanet {
  name: string;
  position: number;
}

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

console.log(planet);
// { name: 'earth' }
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things