0
0
Typescriptprogramming~5 mins

Type predicates in practice in Typescript

Choose your learning style9 modes available
Introduction

Type predicates help your program know exactly what type a value is. This makes your code safer and easier to understand.

When you want to check if a value is a specific type before using it.
When you have a variable that could be one of many types and you want to handle each type differently.
When you want to tell TypeScript about a custom check that narrows down types.
When working with data from outside your program, like user input or API responses.
When you want to avoid errors by making sure a value is the right type before using it.
Syntax
Typescript
function isString(value: unknown): value is string {
  return typeof value === 'string';
}

The value is string part is the type predicate. It tells TypeScript what type the value has if the function returns true.

Type predicates always return a boolean (true or false).

Examples
This function checks if a value is a number.
Typescript
function isNumber(value: unknown): value is number {
  return typeof value === 'number';
}
This function checks if a value is an array.
Typescript
function isArray(value: unknown): value is any[] {
  return Array.isArray(value);
}
This function checks if an object looks like a User with name and age.
Typescript
function isUser(obj: any): obj is { name: string; age: number } {
  return typeof obj.name === 'string' && typeof obj.age === 'number';
}
Sample Program

This program uses a type predicate function isUser to check if each item in the data array is a User. It prints user info only for valid users.

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

function isUser(obj: any): obj is User {
  return typeof obj === 'object' && obj !== null &&
         typeof obj.name === 'string' && typeof obj.age === 'number';
}

const data: unknown[] = [
  { name: 'Alice', age: 30 },
  { name: 'Bob', age: 'unknown' },
  'hello',
  { name: 'Charlie', age: 25 }
];

for (const item of data) {
  if (isUser(item)) {
    console.log(`${item.name} is ${item.age} years old.`);
  } else {
    console.log('Not a valid user:', item);
  }
}
OutputSuccess
Important Notes

Type predicates help TypeScript understand your code better and catch mistakes early.

Always return a boolean from your type predicate functions.

Use type predicates when you want to safely work with values that might have different types.

Summary

Type predicates tell TypeScript what type a value has after a check.

They return true or false and help avoid errors.

Use them to safely handle values with uncertain types.