Background:
TypeScript implements static typing, so sometimes it's necessary to explicitly convert one type to another. For example, when a developer knows the data structure better than the compiler or when working with a typed API whose output types do not match the expected ones. This mechanism is called type casting or type assertions.
Problem:
Type casting in TypeScript does not perform any value transformations at runtime: it merely informs the compiler "trust me." This can lead to errors if the specified cast does not match the actual content of the data. Errors will only appear at runtime, and the compiler will not catch them.
Solution:
TypeScript includes two syntaxes for type casting: angle-bracket (deprecated, not recommended for JSX) and as syntax (recommended).
Code example:
// Syntax using angle brackets (not for .tsx) let someValue: any = "Hello World"; let strLength: number = (<string>someValue).length; // Syntax using as let strLength2: number = (someValue as string).length; // Object type casting (unsafe!) interface Cat { meow(): void; } interface Dog { bark(): void; } let dog: Dog = { bark() {} }; let cat = dog as unknown as Cat; // this works, but bypasses typing!
Key features:
Does type assertion perform automatic value conversion at runtime, like in C# or Java?
No, type assertion simply indicates to the compiler that the variable is of this type. No value conversion occurs — the responsibility lies entirely with the developer.
Can type A be cast to type B without a common structure?
TypeScript will allow this (through double cast, e.g., any or unknown), but it undermines type safety and can lead to runtime errors.
const a = 5 as unknown as string; // not safe!
Is it safe to cast any to a complex type?
No, any disables type checking: casting any to another type is possible, but TypeScript will not catch mismatches, and any errors will only manifest at runtime.
A developer receives an object from the server without structure validation, casts it to the expected type using a simple as SomeType, and uses it in business logic. If the API changes or there is a bug on the server, the application crashes at runtime, with no errors during the build stage.
Pros:
Cons:
A developer first validates the structure of the received object, uses a custom type guard function, and only after successful verification does a type assertion occur.
Pros:
Cons: