Open In App

What is the use of as keyword in TypeScript?

Last Updated : 23 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The as keyword in TypeScript is used for Type Assertion or Type Casting. Type Assertion is a way of telling the TypeScript compiler that you have more information about the type of a value than the TypeScript Compiler. It can also be used with the TypeScript union types in cases when TypeScript is unable to infer the correct type to a variable. It is important to use type assertions carefully so that they align with the actual runtime type and do not throw errors at the runtime.

Syntax:

anyTypeValue as anotherType;

Example: The below code will help you understand the use of as keyword in type assertion.

Javascript




const cmpny: any =
    "GeeksforGeeks";
const len: number =
    (cmpny as string).length;
console.log(cmpny, len);


Output:

GeeksforGeeks 13

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads