← Back to TypeScript Course | Chapter 2: Basic Types | Lesson 11 of 11

Type Assertions

A type assertion tells TypeScript how you want a value to be treated when you know more about its type than the compiler does. Assertions do not change the value at runtime and should be used only when the assertion is correct.

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

typescript
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

typescript
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

typescript
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

typescript
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

typescript
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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.