What is the use of as keyword in TypeScript?
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 = "w3wiki" ; const len: number = (cmpny as string).length; console.log(cmpny, len); |
Output:
w3wiki 13
Contact Us