Typescript Foundations / Basic Types

Type Assertions

šŸŽÆ Type Assertions

Type assertion lets you tell TypeScript what type you believe a value has.

It does not change the actual value at runtime.

šŸ“ Basic Syntax

const value = something as string;

Example:

const data: unknown = "Hello";

const message = data as string;

console.log(message.toUpperCase());

Here, TypeScript treats data as a string.


šŸ”„ Assertion vs Conversion

Type assertion does not convert a value.

const value = "123" as unknown as number;

The value is still a string.

For actual conversion:

const value = Number("123");

Assertion → tells TypeScript the type
Conversion → changes the actual value


🌐 Common Use Cases

šŸ–„ļø DOM Elements

const input =
  document.getElementById("username") as HTMLInputElement;

console.log(input.value);

šŸ“¦ Objects

type User = {
  name: string;
  age: number;
};

const data: unknown = {
  name: "Bhaskar",
  age: 25
};

const user = data as User;

āš›ļø Events

const input = event.target as HTMLInputElement;

console.log(input.value);

šŸ›”ļø Assertion vs Type Guard

Assertion:

const value = data as string;

You are saying: "I know this is a string."

Type guard:

if (typeof data === "string") {
  console.log(data.toUpperCase());
}

You are saying: "Let's check if this is a string."

Type guards are safer when the type is uncertain.


āš ļø Important

Don't use assertions just to remove TypeScript errors:

const value = something as any;

Use assertions only when you actually know the runtime type.