0
0
Typescriptprogramming~5 mins

Type assertions in Typescript

Choose your learning style9 modes available
Introduction

Type assertions tell TypeScript to treat a value as a specific type. It helps when you know more about the value than TypeScript does.

When you get a value from a place TypeScript can't check, like user input or external data.
When you want to tell TypeScript the exact type of a variable to avoid errors.
When you convert a general type to a more specific one to access its properties.
When you want to override TypeScript's inferred type for better code clarity.
Syntax
Typescript
let value = someValue as Type;
// or
let value = <Type>someValue;

Use as Type syntax in modern TypeScript, especially in JSX files.

The angle bracket <Type> syntax works but can conflict with JSX, so prefer as.

Examples
We tell TypeScript that someValue is a string to get its length.
Typescript
let someValue: unknown = "hello";
let strLength: number = (someValue as string).length;
Same as above but using angle bracket syntax.
Typescript
let someValue: unknown = "world";
let strLength: number = (<string>someValue).length;
We assert obj as string to check its length safely.
Typescript
function getLength(obj: string | number) {
  if ((obj as string).length) {
    return (obj as string).length;
  } else {
    return obj.toString().length;
  }
}
Sample Program

This program shows how to use type assertion to treat an unknown value as a string and get its length.

Typescript
let unknownValue: unknown = "TypeScript";

// Tell TypeScript this is a string
let strLength: number = (unknownValue as string).length;

console.log(`The length of the string is ${strLength}`);
OutputSuccess
Important Notes

Type assertions do not change the runtime value, only how TypeScript treats it during checking.

Be careful: wrong assertions can cause runtime errors if the value is not actually of the asserted type.

Summary

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

Use as Type syntax for clarity and compatibility.

They help when TypeScript cannot infer the type correctly.