Sobes.tech
Middle

There is a variable that can be of type Book or Video. How to check the object type? What type does the type guard function return?

sobes.tech AI

Answer from AI

To check the type of an object that can be either Book or Video, TypeScript uses a type guard — a function that checks the type and informs the compiler of the result.

Example:

interface Book {
  title: string;
  author: string;
  pages: number;
}

interface Video {
  title: string;
  duration: number;
  format: string;
}

function isBook(obj: Book | Video): obj is Book {
  return (obj as Book).pages !== undefined;
}

const item: Book | Video = getItem();

if (isBook(item)) {
  // Here TypeScript knows that item is a Book
  console.log(item.author);
} else {
  // Here item is a Video
  console.log(item.duration);
}

The function isBook returns a type predicate obj is Book, which allows the compiler to narrow the type within the conditional block.

There is a variable that can be of type Book or… - sobes.tech