There are times when you know more about a value's type than TypeScript does.
Casting (or Type Assertion) allows you to forcibly override the inferred type.
It tells the compiler, "Trust me, I know exactly what I am doing here."
Casting does not change the actual data at runtime, it only changes the compilation check.
The most common and recommended way to cast a type is using the as keyword.
This syntax is clean and highly compatible with React and JSX formatting.
It immediately stops the compiler from throwing type mismatch errors.
let unknownValue: unknown = "Hello TypeScript";// We tell TypeScript to treat 'unknownValue' strictly as a string let lengthOfStr: number = (unknownValue as string).length;
console.log(lengthOfStr);
An older alternative to the as keyword is the angle bracket syntax < >.
It functions exactly the same way under the hood during the compilation phase.
However, this syntax cannot be used in .tsx files because it conflicts with React tags.
let data: unknown = "Another String";// Cast using angle brackets let stringLength: number = (<string>data).length;
console.log(stringLength);
Overusing casting can be dangerous and hide legitimate structural errors.
Only cast when you are absolutely certain of the incoming data structure.
Stable, error-free DOM interactions ensure search engines can parse your site reliably.
// TypeScript doesn't know this specific input exists, but we do
const myInput = document.getElementById("my-input") as HTMLInputElement;
console.log(myInput.value);
Which keyword is widely recommended for type casting in TypeScript?
Use casting sparingly, mostly when working with third-party libraries or the DOM.
If you find yourself casting constantly, your underlying types might be poorly designed.
Next, we will look at object-oriented features with TypeScript Classes!