What is Type Assertion in TypeScript

In TypeScript, Type Assertions allow developers to explicitly specify the type of a variable to the TypeScript compiler.

 When the compiler cannot infer the type of a variable and the developer is more sure about the type, they can use a type assertion.

Type assertions are a compile-time construct that does not result in runtime type checking or conversion.

They are used when the developer has more precise knowledge of a value’s type than TypeScript’s type inference system can determine.

There are two ways to write type assertions in TypeScript. You can do Type Assertion using angle bracket syntax as shown below.

Besides angel bracket syntax,  as syntax can also be used as shown in the code listing below.

let value: unknown = "ng-India";
let strLength: number = (value as string).length;
console.log(strLength); // 8

Both syntaxes achieve the same result, but as syntax is preferred in modern TypeScript.

Type assertion is mainly used with the unknown type. When working with a value of type unknown, you need to tell TypeScript what type it is before you can use its properties or methods.

let value: unknown = "ng-India";
let strLength: string = (value as string).toUpperCase();
console.log(strLength); // NG-INDIA

Another use case of type assertion is working with union types. When using union types, you can use type assertions to tell TypeScript which specific type you’re working with.

type Fish = { swim: () => void };
type Bird = { fly: () => void };
type Animal = Fish | Bird;

function isFish(animal: Animal): animal is Fish {
    return (animal as Fish).swim !== undefined;
}

Read more about using type assertion for narrowing here – 

Another use case of type assertion is parsing the JSON data. When parsing JSON, TypeScript infers the result as any. You can use type assertions to specify the expected type.

type User = { id: number; name: string };
const jsonString = '{"id": 1, "name": "DJ"}';
const user = JSON.parse(jsonString) as User;

console.log(user.name); // DJ

While working with TypeScript Type Assertions, keep the following points in mind.

  • No runtime check
  • It is a compile-time construct and does not change run-time behavior
  • You should not use unknown or any for every variable. Use them only when necessary with the type assertion.

I hope you now have a better understanding of Type Assertion in TypeScript. Thanks for reading.


Discover more from Dhananjay Kumar

Subscribe to get the latest posts sent to your email.

Published by Dhananjay Kumar

Dhananjay Kumar is founder of NomadCoder and ng-India

Leave a comment

Discover more from Dhananjay Kumar

Subscribe now to keep reading and get access to the full archive.

Continue reading