Type Assertions
In this page:
Basic as Syntax
The as syntax, written like value as SomeType, is the standard way to write a type assertion in modern TypeScript. It tells the compiler to trust your claim about a value's type rather than infer it independently.
Example: Basic as Syntax
let value: unknown = "hello";
let strLength: number = (value as string).length;
console.log(strLength);
Assertions with Objects
Type assertions can describe the expected shape of an object, for example asserting an API response as a specific interface. The assertion helps the compiler understand which properties are safely available afterward, even though it hasn't verified them at runtime.
Example: Assertions with Objects
interface ApiUser {
id: number;
name: string;
}
let response: unknown = { id: 1, name: "Tara" };
let user = response as ApiUser;
console.log(user.name);
Angle-Bracket Syntax
TypeScript also supports an older angle-bracket assertion syntax, <string>value, which behaves identically to as. It's generally avoided in .tsx files, though, since the angle brackets there conflict visually and syntactically with JSX tags.
Example: Angle-Bracket Syntax
let value: unknown = "hello";
let strLength: number = (<string>value).length;
console.log(strLength);
Type Assertions Do Not Convert Values
A type assertion only changes TypeScript's compile-time understanding of a value's type; it performs no actual conversion of the underlying runtime value. Asserting a string as a number doesn't parse it, it just tells the type checker to treat the string as if it were one.
Example: Type Assertions Do Not Convert Values
let value: unknown = "42";
let asNumber = value as number; // no real conversion happens
console.log(typeof asNumber, asNumber); // still "string", "42"
Safe Use of Assertions
Assertions should only be used when you have reliable, out-of-band knowledge about a value's real type, such as knowing an API always returns a particular shape. When that certainty isn't there, a runtime type guard is a much safer way to narrow the type than blindly asserting it.
Example: Safe Use of Assertions
interface ApiResponse {
status: string;
}
function handle(data: unknown) {
if (typeof data === "object" && data !== null && "status" in data) {
console.log((data as ApiResponse).status);
}
}
handle({ status: "ok" });
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: