Use typeof for primitives and instanceof for classes. Interfaces and type aliases don't exist at runtime, so for them write a type guard: a function that checks the shape and returns value is User, as in function isUser(value: unknown): value is User { … }. Inside if (isUser(data)) { … } TypeScript treats data as a User.
TypeScript's types are erased when it compiles to JavaScript. What runs is plain JavaScript, so a runtime check can only use what JavaScript has: typeof, instanceof, Array.isArray, the in operator and comparisons on property values. What TypeScript adds is narrowing: the checker reads those checks and changes a variable's type inside the branch, and a type guard function (the is keyword) lets you teach it a check of your own, which is how you test for an interface.
This page's compiler runs without strict. Every example is written to pass with strict on too, as in most projects, and the strict-mode errors quoted in the notes come from TypeScript 5.9 with --strict. Each example runs on this page: hit Run, then edit the code and run it again.
1A type guard function: value is UserRecommended
To check an interface, check its shape. Take the value as unknown, confirm it is a non-null object, then test each property with in and typeof. Since TypeScript 4.9, "name" in value narrows an unknown object to one that has a name, so the body needs no casts. The return type value is User is the type predicate: the function returns a plain boolean, and wherever it returns true the caller's variable becomes a User. This is the usual way to check data from JSON.parse, an API or localStorage.
interface User { name: string; age: number; email?: string; } // A type guard: a boolean at runtime, and "value is User" tells the // checker what a true result means function isUser(value: unknown): value is User { return ( typeof value === "object" && value !== null && "name" in value && typeof value.name === "string" && "age" in value && typeof value.age === "number" && // optional: absent, or the right type (!("email" in value) || typeof value.email === "string") ); } const inputs: unknown[] = [ JSON.parse('{"name": "Ada", "age": 36}'), JSON.parse('{"name": "Linus", "age": "55"}'), { name: "Grace", age: 85, email: 42 }, { name: "Alan", age: 41, role: "admin" }, null, "Ada", ]; for (const input of inputs) { if (isUser(input)) { // input is User in this branch: name and age are typed console.log(`user: ${input.name.toUpperCase()}, ${input.age + 1} next year`); } else { console.log(`not a user: ${JSON.stringify(input)}`); } }
Output
Ada passes (user: ADA, 37 next year). Linus is rejected because his age is the string "55", and Grace because the optional email is there but is a number. Alan passes despite the extra role: TypeScript types are structural, so a guard checks what the type needs and lets the rest through. null and the string "Ada" fail the object test. Keep the value !== null: typeof null is "object". Leave it out and, with strict on, the checker stops at the in with error TS18047: 'value' is possibly 'null'. Without strict it compiles, and isUser(null) throws Cannot use 'in' operator to search for 'name' in null. For parsing JSON into typed objects end to end, see parse JSON into a typed object.
2typeof for primitives, instanceof for classes
For built-in types you don't need a guard function: TypeScript narrows on typeof and instanceof directly. typeof answers for string, number, boolean, bigint, symbol, undefined and function, and says "object" for everything else. instanceof works on classes, your own and built-ins like Date, Map and Error, because a class is a real value at runtime. Each check removes its type from the union, so after the last one only one type is left.
// typeof narrows primitives, instanceof narrows classes: no helper needed function describe(value: string | number | Date | string[]): string { if (typeof value === "string") return `string, ${value.length} chars`; if (typeof value === "number") return `number, ${value.toFixed(2)}`; if (value instanceof Date) return `Date, ${value.toISOString().slice(0, 10)}`; return `string[], ${value.join("+")}`; // the only type left } console.log(describe("hello")); console.log(describe(Math.PI)); console.log(describe(new Date(Date.UTC(2026, 10, 19)))); console.log(describe(["a", "b"])); // What typeof returns: only these eight strings exist const samples: unknown[] = [null, [1, 2], new Date(0), () => 1, 10n, undefined]; console.log(samples.map((s) => typeof s).join(" ")); console.log(Array.isArray([1, 2]), Array.isArray({ length: 2 })); class Dog { constructor(public name: string) {} bark(): string { return `${this.name}: Woof`; } } class Cat { constructor(public name: string) {} meow(): string { return `${this.name}: Meow`; } } function speak(pet: Dog | Cat): string { return pet instanceof Dog ? pet.bark() : pet.meow(); } console.log(speak(new Dog("Rex")), "|", speak(new Cat("Tom"))); // instanceof checks the prototype chain, not the shape. This object // has Dog's shape, so the checker accepts it, but no class made it. const lookalike: Dog = { name: "Fido", bark: () => "Fido: Woof" }; console.log(lookalike instanceof Dog); try { console.log(speak(lookalike)); } catch (err) { console.log((err as Error).message); }
Output
describe prints string, 5 chars, number, 3.14, Date, 2026-11-19 and string[], a+b; in the last line no check was needed, because string[] was the only type left. The typeof line reads object object object function bigint undefined: null, an array and a Date are all "object", so use Array.isArray for arrays (true false) and instanceof for class instances. speak prints Rex: Woof | Tom: Meow. The last lines are the catch with instanceof: the checker accepts any object with Dog's shape as a Dog, but at runtime instanceof only recognises objects the class created. The lookalike prints false and falls into the cat branch: pet.meow is not a function. Objects from JSON.parse are the common case: a Dog sent through JSON and parsed back printed false {"name":"Rex"}. Check those with a guard (section 1) or build an instance from them.
3Why instanceof doesn't work on an interface
The most common first attempt is value instanceof User with an interface. It can't work: instanceof needs a constructor function to compare prototypes with, and an interface leaves nothing behind in the JavaScript output. TypeScript rejects it before anything runs, so this example prints nothing and exits with code 1.
interface User { name: string; } const value: unknown = JSON.parse('{"name": "Ada"}'); // Interfaces are erased when TypeScript compiles to JavaScript, // so there is no User object for instanceof to look at if (value instanceof User) { console.log(`Hello, ${value.name}`); }
Output
The run stops with error TS2693: 'User' only refers to a type, but is being used as a value here. and, because the check narrowed nothing, the next line adds error TS2339: Property 'name' does not exist on type 'unknown'. (with strict on, that second one reads error TS18046: 'value' is of type 'unknown'.). The same error appears for a type alias. There are two fixes: replace the check with a guard, isUser(value) from section 1, or, if you want instanceof, make User a class and create real instances with new.
4Unions of interfaces: in and a kind field
When you already know a value is one of a few interfaces, you only need to tell the members apart, and two checks do it without a guard function. "swim" in pet narrows to the members that have a swim property. Better still, give every member a literal field such as kind, a discriminant: comparing it with === narrows to exactly one member. For data from outside, one guard turns unknown into the union, and the kind checks take over from there.
interface Fish { swim(): string; } interface Bird { fly(): string; } // "in" narrows a union by a property only one member has function move(pet: Fish | Bird): string { if ("swim" in pet) return pet.swim(); // pet is Fish return pet.fly(); // pet is Bird } console.log(move({ swim: () => "splash" })); console.log(move({ fly: () => "flap" })); // A discriminant: a literal "kind" field every member carries type Shape = | { kind: "circle"; radius: number } | { kind: "rect"; width: number; height: number }; function area(shape: Shape): number { if (shape.kind === "circle") return Math.PI * shape.radius ** 2; return shape.width * shape.height; // shape is the rect here } const shapes: Shape[] = [ { kind: "circle", radius: 1 }, { kind: "rect", width: 3, height: 4 }, ]; for (const s of shapes) console.log(s.kind, area(s).toFixed(2)); // The same check works on data from outside, after one guard function isShape(value: unknown): value is Shape { if (typeof value !== "object" || value === null || !("kind" in value)) { return false; } const v = value as Record<string, unknown>; if (v.kind === "circle") return typeof v.radius === "number"; if (v.kind === "rect") { return typeof v.width === "number" && typeof v.height === "number"; } return false; } const raw: unknown[] = JSON.parse( '[{"kind":"rect","width":2,"height":5},{"kind":"square","side":2}]', ); for (const item of raw) { if (isShape(item)) console.log(`area ${area(item)}`); else console.log(`rejected ${JSON.stringify(item)}`); }
Output
move prints splash and flap, and area prints circle 3.14 and rect 12.00: inside each branch only that member's fields (radius, or width and height) are available. The parsed rectangle passes isShape (area 10), and the unknown kind is turned away: rejected {"kind":"square","side":2}. Inside isShape, the as Record<string, unknown> cast is safe because it only says the properties are unknown, and each one is checked before the function returns true. To make the compiler prove that a switch on kind handles every member, see check a switch is exhaustive.
5Check for an array of strings
Array.isArray(value) narrows an unknown to any[], which says nothing about the items. To know it is a string[], test every item as well, and wrap both tests in a guard so the caller gets the narrowed type. A generic isArrayOf that takes the item guard as a parameter covers every element type with one function.
// An array check has two parts: is it an array, and is every item right function isStringArray(value: unknown): value is string[] { return Array.isArray(value) && value.every((item) => typeof item === "string"); } // A reusable version: pass the guard for one item function isArrayOf<T>( value: unknown, isItem: (item: unknown) => item is T, ): value is T[] { return Array.isArray(value) && value.every(isItem); } const isNumber = (x: unknown): x is number => typeof x === "number"; const tags: unknown = JSON.parse('["ts", "node", "types"]'); if (isStringArray(tags)) { console.log(tags.map((t) => t.toUpperCase()).join(", ")); } const values: unknown[] = [["a", "b"], ["a", 1], "ab", [], [1, 2, 3]]; for (const v of values) { console.log(JSON.stringify(v).padEnd(10), isStringArray(v), isArrayOf(v, isNumber)); } // TypeScript 5.5+ infers a guard from a simple filter callback, // so the result is string[], not (string | number)[] const mixed: (string | number)[] = ["a", 1, "b", 2]; const strings = mixed.filter((x) => typeof x === "string"); console.log(strings.map((s) => s.repeat(2)));
Output
The parsed tags pass and print TS, NODE, TYPES, with t typed as string in the map. In the table, ["a",1] fails on its second item and "ab" fails because a string is not an array. Note the [] row: true true. every on an empty array is true, so an empty array is both a string[] and a number[], which is correct for the types, but add a length check if your data must not be empty. The last line, [ 'aa', 'bb' ], shows TypeScript 5.5's inferred type predicates: the filter callback (x) => typeof x === "string" is read as a guard, so strings is a string[] and s.repeat type-checks. Before 5.5 you had to write (x): x is string => yourself, and you still do for callbacks the checker can't infer.
6What the is keyword does, and asserts functions
A function that returns boolean tells the caller nothing about the type, so a plain function isPoint(value: unknown): boolean can be true and value stays unknown. value is Point is what connects the result to the type. TypeScript does not verify that the body matches the predicate, though: it trusts it, and a careless guard lies to the checker. The related asserts value is Point form throws instead of returning false, and narrows the variable for the rest of the block.
interface Point { x: number; y: number; } function isPoint(value: unknown): value is Point { return ( typeof value === "object" && value !== null && "x" in value && typeof value.x === "number" && "y" in value && typeof value.y === "number" ); } // A guard is trusted, not checked: this one forgets y, // and TypeScript believes it all the same function isPointSloppy(value: unknown): value is Point { return typeof value === "object" && value !== null && "x" in value; } const data: unknown = { x: 3 }; console.log(isPoint(data), isPointSloppy(data)); if (isPointSloppy(data)) { try { console.log(data.y.toFixed(1)); // compiles: data is Point here } catch (err) { console.log((err as Error).message); } } // An assertion function throws instead of returning false, // and narrows the variable for the rest of the block function assertPoint(value: unknown): asserts value is Point { if (!isPoint(value)) { throw new TypeError(`not a Point: ${JSON.stringify(value)}`); } } const inputs: unknown[] = [{ x: 1, y: 2 }, { x: 3 }]; for (const input of inputs) { try { assertPoint(input); // input is Point from here on console.log(`length ${Math.hypot(input.x, input.y)}`); } catch (err) { console.log((err as Error).message); } }
Output
For { x: 3 } the full guard says false and the sloppy one true, so the sloppy branch runs, data.y type-checks as a number, and the call fails at runtime: Cannot read properties of undefined (reading 'toFixed'). Test every property the type promises. With assertPoint, the good input prints length 2.23606797749979 and the bad one throws not a Point: {"x":3} before any property is read. Swap the predicate for boolean and using the value after the check fails to compile: error TS18046: 'data' is of type 'unknown'. with strict on, and error TS2339: Property 'x' does not exist on type 'unknown'. on this page's compiler.
7Which should you use?
| Check | Works on | Narrows to | Watch out for |
|---|---|---|---|
| typeof x === "string" | Primitives, functions | That primitive | typeof null is "object" |
| x instanceof Dog | Classes, built-ins like Date | That class | Plain and JSON objects never match |
| Array.isArray(x) | Arrays | any[] (items unchecked) | Check the items too |
| "swim" in x | Union members, unknown objects | Members with that property | Throws on null: check the object first |
| x.kind === "circle" | Discriminated unions | Exactly one member | Every member needs the field |
| isUser(x): x is User | Interfaces, type aliases, anything | User | The body is trusted, not verified |
| asserts x is User | Same as a guard | User for the rest of the block | Throws instead of returning false |
Frequently asked questions
How do I check if an object implements an interface in TypeScript?
Write a type guard that checks the shape: function isUser(value: unknown): value is User returning typeof value === "object" && value !== null && "name" in value && typeof value.name === "string", with one test per property. Then if (isUser(data)) narrows data to User. Interfaces are erased at compile time, so there is no automatic check; instanceof only works for classes.
Why does instanceof give "'User' only refers to a type, but is being used as a value here"?
That is TS2693, and it means User is an interface or a type alias. Types do not exist in the compiled JavaScript, and instanceof needs a class (a constructor function) to compare with at runtime. Use a type guard function instead, or declare User as a class and create values with new User(...).
What does the is keyword do in TypeScript?
It declares a type predicate as a function's return type: function isFish(pet: Fish | Bird): pet is Fish. The function returns a boolean at runtime, and TypeScript narrows the argument to Fish where the result is true and to Bird where it is false. With a plain boolean return type nothing is narrowed. The checker does not verify the body, so the guard must really test what it claims.
How do I check if a value is an array of strings?
Combine Array.isArray with every: Array.isArray(value) && value.every((item) => typeof item === "string"), inside a guard returning value is string[]. Array.isArray alone only tells you it is an array. An empty array passes, because every on [] is true.
Can I compare typeof with my own type, like typeof value === "User"?
No. typeof only ever returns one of eight strings ("string", "number", "bigint", "boolean", "symbol", "undefined", "object", "function"), and TypeScript rejects the comparison with error TS2367, which lists those eight strings and ends and '"User"' have no overlap. For a union of string literals, keep the values in an as const array and check with includes in a guard: isRole("editor") printed true and isRole("owner") printed false.
Can TypeScript generate a type guard from an interface automatically?
Not the compiler itself: types are erased, so it emits no runtime checks. TypeScript 5.5 and later only infer guards for simple callbacks such as (x) => typeof x === "string". For larger shapes, write the guard by hand or use a schema validation library such as Zod or Valibot, where you define the schema once and derive the static type from it, so the check and the type cannot drift apart.
Run it yourself
Open any of these in the full TypeScript editor to tweak, run and share.
TypeScript playground