18. How does the as keyword work for type assertions? Provide an example.

The as keyword in TypeScript is used for type assertions, which is a way of telling the compiler that a certain object has a specific type, even though the compiler might not know it. This is useful when you're confident about the type of an object but the compiler cannot infer it.

Example:

let value: any = 'Hello'; let length: number = (value as string).length; // Type assertion that 'value' is a string.

In this example, we use as string to tell the compiler that the value variable is of type string, even though it was initially declared as any.

Type assertion does not change the actual type of the variable at runtime, it only helps the compiler in static analysis.

devFlipCards 2025

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.