CodeBlanks Logo Icon CodeBlanks

User-defined type guard

Learn to write custom type guards with is.

User-defined type guard

A user-defined type guard uses a predicate of the form x is T as a function's return type. When the function returns true, TypeScript narrows the parameter to type T. It's the way to safely process wide types like unknown.

function isString(x: unknown): x is string {
  return typeof x === "string";
}

function upper(v: unknown): string {
  if (isString(v)) {
    return v.toUpperCase();  // v: string
  }
  return "";
}

Handling unknown with is

Type guards are especially useful when working with unknown. When a value's structure is unknown, safe narrowing is done via a guard function. Making the guard reusable centralizes the narrowing logic.

function isNumber(x: unknown): x is number {
  return typeof x === "number";
}

function double(v: unknown): number {
  if (isNumber(v)) {
    return v * 2;  // v: number
  }
  return 0;
}

Practice Handle unknown with an isString guard

Define an isString(x: unknown): x is string type guard function (with a typeof x === "string" check inside). Write an upper(v: unknown): string function: if isString(v) is true, return v.toUpperCase(); otherwise return "". Print results via console.log(upper("hello")) and console.log(upper(42)).

Starter code

index.ts
// isString guard fonksiyonunu tanımla (unknown parametre, string predicate)

// upper(v: unknown): string fonksiyonunu guard ile yaz

// upper("hello") ve upper(42) sonuçlarını yazdır

Sample solution

index.ts
function isString(x: unknown): x is string {
  return typeof x === "string";
}

function upper(v: unknown): string {
  if (isString(v)) {
    return v.toUpperCase();
  }
  return "";
}

console.log(upper("hello"));
console.log(upper(42));

Expected output

HELLO

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does a return type of the form x is T do?

  • It produces a value at runtime
  • It auto-generates the T type
  • When the function returns true, it narrows x to T Correct answer
  • It makes the function run faster

Explanation: The x is T predicate tells TypeScript that the parameter is T when the function returns true; in an if condition the parameter is narrowed to T.

2 is predicate definition

Question
function isString(x: unknown): ____ {
  return typeof x === "string";
}
Answer
function isString(x: unknown): x is string {
  return typeof x === "string";
}

Explanation: The x is string predicate tells TypeScript that x is a string when the function returns true, providing narrowing.

3 Type guard parts

Term Meaning
x is T type guard predicate
isString(x) narrows x to string if true
unknown türü safe narrowing with guard
typeof x === "string" runtime check

All lessons in Advanced