QA
Intermediate LevelJavaScript & TypeScript

How do TypeScript custom Type Guards (is keyword) and Assertion Functions work?

❓ Interview Prompt: Explain custom type predicate functions (`arg is Type`) and assertion signatures (`asserts condition`).

Custom Type Guards are functions returning a boolean that instruct the TypeScript compiler to narrow a variable's type when the function returns true.

1. Type Predicate (val is Type):

Function return type signature stating: "If this function returns true, val is of type Type".

2. Assertion Signature (asserts val is Type):

Function signature stating: "If this function finishes executing without throwing an error, val is of type Type".

Code Implementation Example

typescript
interface Fish { swim(): void }
interface Bird { fly(): void }

// Custom Type Guard predicate function
function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}

function move(pet: Fish | Bird) {
  if (isFish(pet)) {
    pet.swim(); // ✅ TS knows pet is Fish!
  } else {
    pet.fly();  // ✅ TS knows pet is Bird!
  }
}

// Custom Assertion Function
function assertIsString(val: unknown): asserts val is string {
  if (typeof val !== 'string') {
    throw new TypeError('Value is not a string!');
  }
}

let data: unknown = 'Hello';
assertIsString(data);
console.log(data.toUpperCase()); // ✅ TS knows data is string after assertion!
💡Custom type predicate with is keyword and assertion signature with asserts keyword.
🎯 Interview Key Takeaway

Custom type guards using "arg is Type" allow custom domain logic to narrow complex types across your application.

#TypeScript#Type Guards#Predicates#Intermediate
Back to all JavaScript & TypeScript Questions→

More JavaScript & TypeScript Interview Questions

Beginner LevelJavaScript & TypeScript

What are the differences between var, let, and const in JavaScript?

Beginner LevelJavaScript & TypeScript

What are the JavaScript data types and the difference between primitives and objects?

Beginner LevelJavaScript & TypeScript

What is the difference between == (loose equality) and === (strict equality)?