Type casting (also known as type assertion) allows you to tell the TypeScript compiler to treat a value as a specific target type when you have more information than the type checker.
as Syntax (Recommended): expression as TargetType.<TargetType>expression (Not compatible with JSX/React).expression as unknown as TargetType (For forced conversions).// DOM Element Casting
// document.getElementById returns HTMLElement | null
const inputElement = document.getElementById("username-input") as HTMLInputElement;
if (inputElement) {
inputElement.value = "john_doe"; // Valid because compiler knows it's an HTMLInputElement
}
// Unknown API payload casting
const rawJson: unknown = '{"id": "usr_99", "score": 95}';
interface UserPayload {
id: string;
score: number;
}
// Casting unknown to UserPayload after runtime check
if (typeof rawJson === "string") {
const parsed = JSON.parse(rawJson) as UserPayload;
console.log(`User ID: ${parsed.id}, Score: ${parsed.score}`);
}
// Double Assertion (Use with extreme caution!)
const numericString = "12345";
// const num = numericString as number; // Compiler Error: Conversion of type 'string' to type 'number' may be a mistake
const forcedNum = (numericString as unknown) as number; // Bypasses compiler safety
as Over Angle Brackets: as syntax works universally across .ts and .tsx React files.val as number does not convert a runtime string "123" into a number. Use JavaScript functions like Number(val) for runtime casting.as unknown as Type) bypasses type safety and should be reserved for legacy code migration or external mocks.Obtain a element using document.getElementById('app') and cast it to HTMLDivElement using as syntax.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With