EasyJavaScriptTypeScript

Type Guards (x is T)

TypeScriptTypes

Implement five type guard functions. In TypeScript, a type guard is a function whose return type is x is T — a type predicate that narrows the type of a variable in the surrounding scope:

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

const value: unknown = 'hello';
if (isString(value)) {
  value.toUpperCase(); // TypeScript knows value is string here ✅
}

The five guards

GuardPasses forFails for
isString'hello'42, null
isNumber42'42', NaN
isArray[], [1,2,3]{}, null
isNullishnull, undefined0, '', false
isObject{ a: 1 }[], null, functions

TypeScript rules

  • isNumber must return false for NaN (it is typeof 'number' but not a valid number)
  • isObject must return false for arrays (they are objects but not plain objects)
  • isObject must return false for null (typeof null === 'object' is JS's famous bug)

Sample tests

Test #1string primitive is a string
Input: ["hello","isString"]
Output: true
Test #2number is not a string
Input: [42,"isString"]
Output: false
Test #3number primitive is a number
Input: [42,"isNumber"]
Output: true
Test #4null is not a number (NaN is also rejected — typeof NaN === "number" but !Number.isNaN)
Input: [null,"isNumber"]
Output: false
Test #5empty array is an array
Input: [[],"isArray"]
Output: true
Test #6plain object is not an array
Input: [{},"isArray"]
Output: false
Test #7null is nullish (undefined behaves the same)
Input: [null,"isNullish"]
Output: true
Test #8plain object is an object
Input: [{},"isObject"]
Output: true
Test #9array is not a plain object
Input: [[],"isObject"]
Output: false