keepcalculator

06 Numbers and Powers

Check an Object Against a TypeScript Interface

Card No. 06·80773 · Updated · Standard formula, shown below

This guide shows you how to verify that a JavaScript object matches a TypeScript interface at runtime. Since TypeScript interfaces are erased during compilation, you’ll need a runtime check strategy—this article covers manual validation, type guards, and schema libraries. You’ll learn the practical steps to ensure your data is safe before using it.

What You’ll Need

  • A TypeScript project (any version 3.x or later works)
  • Basic understanding of interfaces and type annotations
  • Optional: a schema validation library like Zod or io-ts (we’ll cover when to use them)

Step-by-Step

  1. Define your interface. Start with the shape you expect. For example:

    interface User {
      id: number;
      name: string;
      email?: string;
      roles: string[];
    }

    Note that optional properties (marked with ?) require special handling in checks.

  2. Write a type guard function. A type guard is a function that returns a boolean and uses a type predicate. It tells TypeScript that if the function returns true, the argument is of that type.

    function isUser(obj: any): obj is User {
      return (
        typeof obj === 'object' &&
        obj !== null &&
        typeof obj.id === 'number' &&
        typeof obj.name === 'string' &&
        (obj.email === undefined || typeof obj.email === 'string') &&
        Array.isArray(obj.roles) &&
        obj.roles.every((r: any) => typeof r === 'string')
      );
    }

    This manual approach gives you full control and doesn’t require extra dependencies.

  3. Use the guard in your code. After the check, TypeScript narrows the type automatically:

    function processUser(data: unknown) {
      if (isUser(data)) {
        console.log(data.name.toUpperCase()); // data is now User
      } else {
        throw new Error('Invalid user object');
      }
    }
  4. Handle nested objects and arrays. For complex interfaces, check each nested property recursively. For example, if you have address: { city: string }, you need a separate guard for the address object or inline the checks.
  5. Consider using a schema library (recommended for larger projects). Libraries like Zod or io-ts generate validators from a schema definition. With Zod:

    import { z } from 'zod';
    
    const UserSchema = z.object({
      id: z.number(),
      name: z.string(),
      email: z.string().optional(),
      roles: z.array(z.string()),
    });
    
    type User = z.infer<typeof UserSchema>;
    
    const result = UserSchema.safeParse(someData);
    if (result.success) {
      // result.data is typed as User
    } else {
      console.error(result.error);
    }

    This approach is less error-prone and gives you detailed error messages.

  6. For very simple checks, use a utility like class-validator with decorators (if you’re using classes) or write a small helper that compares keys. But the type guard is the most direct.

Common Mistakes

  • Forgetting null check: typeof null === 'object' is true, so always check obj !== null.
  • Ignoring optional properties: If you don’t check that email is either undefined or a string, your guard will reject valid objects.
  • Using typeof for arrays: typeof [] === 'object' is true, so use Array.isArray().
  • Assuming TypeScript does runtime checks: It doesn’t. Interfaces are compile-time only.
  • Using as to cast instead of validating: Casting (data as User) doesn’t check anything; it just tells TypeScript to trust you.

Tips

  • Write small, reusable type guards for each interface and compose them for larger objects.
  • Use unknown instead of any for function parameters that come from external sources (APIs, user input). This forces you to validate properly.
  • If you use a schema library, keep the schema as the single source of truth and derive the TypeScript type from it (as shown with z.infer).
  • Test your guards with edge cases: empty objects, arrays with wrong item types, missing optional properties, and null.
  • For performance-critical code, manual guards are faster than schema libraries, but the difference is negligible for most applications.

Troubleshooting

Your guard always returns false. Check for a typo in property names. Also verify that you’re not accidentally checking for undefined on required properties—if a property is missing, typeof obj.prop === 'undefined' is true, but you want it to be the expected type.

TypeScript still complains after the guard. Make sure the guard uses a type predicate (obj is User). If you just return a boolean, TypeScript won’t narrow the type.

You get an error about obj being implicitly any. Explicitly type the parameter as any or unknown in the guard function.

Nested objects are not validated. Your guard only checks the top level. Add recursive checks for each nested object.

Schema library gives unexpected errors. Read the error messages carefully; they usually point to the exact path of the invalid property (e.g., roles.0).

Frequently Asked Questions

Can I use instanceof to check an interface?

No, instanceof works only with classes, not interfaces. Interfaces are erased at runtime.

Is there a built-in TypeScript function to validate interfaces?

No. TypeScript doesn’t provide runtime validation. You need to write your own or use a library.

What’s the difference between a type guard and a schema validator?

A type guard is a hand-written function that checks the shape. A schema validator (like Zod) defines a schema and generates a validator, often with better error messages and type inference.

Should I validate every object I receive from an API?

Yes, especially if the API is external or the data is user-provided. Even internal APIs can change, so validating at boundaries is a good practice.

Can I use Object.keys() to check for extra properties?

Yes, if you want to reject objects with unknown properties. But be careful: TypeScript allows excess properties only in object literals, not in variables. So you may need to decide if extra properties are allowed.

Does using a schema library slow down my app?

It adds a small overhead, but for most apps it’s negligible. If you’re validating large arrays frequently, manual guards might be faster.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →