0
0
Typescriptprogramming~5 mins

Custom type guard functions in Typescript

Choose your learning style9 modes available
Introduction

Custom type guard functions help you check if a value is a specific type. This makes your code safer and easier to understand.

When you want to check if a variable is a certain object type before using it.
When you receive data from outside your program and need to confirm its shape.
When you want to narrow down union types to a specific type in your code.
When you want to avoid errors by making sure a value has the properties you expect.
Syntax
Typescript
function isTypeName(value: unknown): value is TypeName {
  // return true if value matches TypeName
}

The function returns a boolean.

The return type uses value is TypeName to tell TypeScript about the type check.

Examples
This checks if a value is a string.
Typescript
function isString(value: unknown): value is string {
  return typeof value === 'string';
}
This checks if a value looks like a User object.
Typescript
interface User {
  name: string;
  age: number;
}

function isUser(value: unknown): value is User {
  return typeof value === 'object' && value !== null &&
         'name' in value && typeof (value as any).name === 'string' &&
         'age' in value && typeof (value as any).age === 'number';
}
Sample Program

This program defines two types: Cat and Dog. It uses a custom type guard isCat to check if a pet is a Cat. Then it calls the correct sound method.

Typescript
interface Cat {
  name: string;
  meow: () => void;
}

interface Dog {
  name: string;
  bark: () => void;
}

function isCat(pet: unknown): pet is Cat {
  return typeof pet === 'object' && pet !== null && 'meow' in pet;
}

function speak(pet: Cat | Dog) {
  if (isCat(pet)) {
    pet.meow();
  } else {
    pet.bark();
  }
}

const myCat: Cat = { name: 'Whiskers', meow: () => console.log('Meow!') };
const myDog: Dog = { name: 'Rex', bark: () => console.log('Woof!') };

speak(myCat);
speak(myDog);
OutputSuccess
Important Notes

Custom type guards help TypeScript understand your checks better.

Always check for null when testing if a value is an object.

Use in operator to check if a property exists on an object.

Summary

Custom type guard functions check if a value is a specific type.

They return value is TypeName to help TypeScript narrow types.

Use them to make your code safer and clearer.