Type assertions tell TypeScript to treat a value as a specific type.
Getting Started
What is TypeScript?
Basic Types
Types & Interfaces
Async TypeScript
Promises & Async/Await
TypeScript
Intermediate
FREE
Type Assertions
Lesson 2 of 17
Intermediate
Interactive
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);