Skip to content
Home Tutorials Roadmaps Courses
Log in Join free
Tutorials TypeScript Type Assertions
TypeScript Intermediate FREE

Type Assertions

Lesson 2 of 17 Intermediate Interactive

Type assertions tell TypeScript to treat a value as a specific type.

Syntax

TYPESCRIPT
let value: unknown = "hello";
let length: number = (value as string).length;

// Angle bracket syntax (not in JSX)
let len = <string>value).length;
Type Assertions
TYPESCRIPT
let value: unknown = "Hello, TypeScript";

// Type assertion
let strLen: number = (value as string).length;
console.log(strLen);

// Alternative syntax
let strLen2: number = (<string>value).length;

// Non-null assertion
let maybeNull: string | null = "hello";
let definite: string = maybeNull!;

// Const assertion
let config = {
    host: "localhost",
    port: 3000
} as const;

console.log(config.host);