TypeScript is a powerful superset of JavaScript that provides static typing, which helps in detecting errors early in the development process. One of the features that TypeScript provides is Type Assertion. Type Assertion is a way to tell the TypeScript compiler about the expected type of a value, even when the type cannot be inferred automatically. In this tutorial, we will explore what Type Assertion is, how it works, and how it can be used in TypeScript.
What is Type Assertion?
Type Assertion is a way to tell the TypeScript compiler the type of a value. It is useful in situations where the type of a value cannot be inferred automatically by the TypeScript compiler. For example, if you have a value of type any, which can represent any type, you can use Type Assertion to tell the compiler the expected type of the value.
There are two ways to perform Type Assertion in TypeScript:
Angle bracket notation:
Angle bracket notation is the older syntax for performing Type Assertion in TypeScript. It looks like this:
let someValue: any = "Hello, world!";
let strLength: number = (<string>someValue).length;In this example, we have a variable someValue of type any. We want to get the length of the string value of someValue. We use Angle bracket notation to perform Type Assertion and tell the TypeScript compiler that someValue is a string.
As keyword:
The newer and recommended syntax for performing Type Assertion in TypeScript is the as keyword. It looks like this:
let someValue: any = "Hello, world!";
let strLength: number = (someValue as string).length;In this example, we use the as keyword to perform Type Assertion and tell the TypeScript compiler that someValue is a string.
Both syntaxes work in the same way and achieve the same result. However, the as keyword is preferred over the Angle bracket notation because it is less prone to conflicts with JSX syntax and is more readable.
How Type Assertion works
When Type Assertion is performed, the TypeScript compiler assumes that the type provided is the actual type of the value. This means that if the Type Assertion is incorrect, it can result in runtime errors.
let someValue: any = 5;
let strLength: number = (someValue as string).length; // Runtime error: Cannot read property 'length' of undefined.In this example, we have a variable someValue of type any. We use the as keyword to perform Type Assertion and tell the TypeScript compiler that someValue is a string. However, someValue is actually a number, and when we try to access the length property of someValue, a runtime error occurs because numbers do not have a length property.
Using Type Assertion in TypeScript
Type Assertion can be used in various situations in TypeScript. Here are some examples:
Working with DOM elements:
When working with DOM elements, the type of the element cannot be inferred automatically by the TypeScript compiler. Type Assertion can be used to tell the compiler the expected type of the element.
let elem = document.getElementById("myDiv") as HTMLDivElement;
elem.style.color = "red";In this example, we use Type Assertion to tell the TypeScript compiler that elem is an HTMLDivElement. We can then access the style property of elem without any errors.
Working with third-party libraries:
When working with third-party libraries that do not have TypeScript definitions, the type of the library functions and objects cannot be inferred automatically by the TypeScript compiler. Type Assertion can be used to tell the compiler the expected type of the library functions and objects.
import * as moment from "moment";
let date = moment() as moment.Moment;
let formattedDate = date.format("YYYY-MM-DD");In this example, we use Type Assertion to tell the TypeScript compiler that date is a Moment object from the moment library. We can then use the format function of date without any errors.
Working with APIs:
When working with APIs, the type of the API response cannot be inferred automatically by the TypeScript compiler. Type Assertion can be used to tell the compiler the expected type of the API response.
interface User {
name: string;
age: number;
}
fetch("https://example.com/api/user")
.then(response => response.json() as Promise<User>)
.then(user => console.log(user.name, user.age));In this example, we use Type Assertion to tell the TypeScript compiler that the API response is a Promise that resolves to a User object. We can then access the name and age properties of the User object without any errors.
Conclusion
Type Assertion is a powerful feature in TypeScript that allows developers to tell the TypeScript compiler the expected type of a value. It is useful in situations where the type of a value cannot be inferred automatically by the TypeScript compiler. Type Assertion can be performed using Angle bracket notation or the as keyword. It is important to ensure that the Type Assertion is correct to avoid runtime errors. Type Assertion can be used in various situations in TypeScript, such as working with DOM elements, third-party libraries, and APIs.