Skip to content

Type Guards

Type guards are a simple way to check what type a value really is while your code is running. They help TypeScript understand your logic so it can give better autocomplete, prevent errors, and make your code safer.

A type guard is just a function (or expression) that checks if a value has a certain shape or type.

When a type guard returns true, TypeScript narrows the type — meaning it knows more about the value afterwards.

Example

if (isMedia(image)) {
// Inside here TypeScript knows: image is Media
}

Without a type guard, TypeScript might think the value could be multiple types. With a type guard, it becomes specific.


Use type guards when:

  • A value can be multiple types (union types)
  • You receive data from APIs, forms, or external sources
  • You need to check if an object has certain properties (for example React component props)
  • You want cleaner, safer if checks

Example use cases

function handleImage(input: PayloadImage | number) {
if (isPayloadImage(input)) {
// treat as Media
console.log(input.url);
} else {
// it's just a number
console.log("Image ID:", input);
}
}

Type guards make code easier to understand and reduce “undefined” errors.


A type guard is just a function that:

  1. Takes a value
  2. Performs a runtime check
  3. Returns value is SomeType in the function signature

Example

export function isPayloadImage(value: unknown): value is Media {
return !!value && typeof value !== 'number' && 'url' in value;
}

What this does:

  • !!value → value must be defined
  • typeof value !== 'number' → it’s not a number
  • 'url' in value → it has a url property, so it looks like a Media object

When the function returns true, TypeScript now knows the value is a Media.

function isSomething(value: unknown): value is Something {
return // your logic to check if `value` is of type `Something`
}

Should describe what you’re checking:

  • isUser
  • isMedia
  • isValidConfig

Use is or has at the start so it’s instantly clear it’s a check.

Usually typed as unknown or a union of possible types:

(value: unknown)

unknown means: “We don’t trust this value yet — we need to check it first.”

This is the “magic” part:

value is Something

This tells TypeScript:
“If this function returns true, you can safely treat the value as Something.”

This should look like real runtime validation. Typical checks:

typeof value === "string"
"id" in value
typeof value === "object" && value !== null && "url" in value
Array.isArray(value)

If your check returns true, TypeScript narrows the type.


Below are the type guards already included in the boilerplate:

isPayloadImage src/guards/payload-object.ts
Checks whether a PayloadImage is actually a Media object (and not just an ID).