What is the use of as keyword in TypeScript?
Last Updated :
23 Feb, 2024
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
Share your thoughts in the comments
Please Login to comment...