You can achieve what you want without the instanceof keyword as you can write custom type guards now:

interface A {
    member: string;
}

function instanceOfA(object: any): object is A {
    return 'member' in object;
}

var a: any = {member: "foobar"};

if (instanceOfA(a)) {
    alert(a.member);
}

Lots of Members

If you need to check a lot of members to determine whether an object matches your type, you could instead add a discriminator. The below is the most basic example, and requires you to manage your own discriminators... you'd need to get deeper into the patterns to ensure you avoid duplicate discriminators.

interface A {
    discriminator: 'I-AM-A';
    member: string;
}

function instanceOfA(object: any): object is A {
    return object.discriminator === 'I-AM-A';
}

var a: any = {discriminator: 'I-AM-A', member: "foobar"};

if (instanceOfA(a)) {
    alert(a.member);
}
Answer from Fenton on Stack Overflow
Top answer
1 of 16
581

You can achieve what you want without the instanceof keyword as you can write custom type guards now:

interface A {
    member: string;
}

function instanceOfA(object: any): object is A {
    return 'member' in object;
}

var a: any = {member: "foobar"};

if (instanceOfA(a)) {
    alert(a.member);
}

Lots of Members

If you need to check a lot of members to determine whether an object matches your type, you could instead add a discriminator. The below is the most basic example, and requires you to manage your own discriminators... you'd need to get deeper into the patterns to ensure you avoid duplicate discriminators.

interface A {
    discriminator: 'I-AM-A';
    member: string;
}

function instanceOfA(object: any): object is A {
    return object.discriminator === 'I-AM-A';
}

var a: any = {discriminator: 'I-AM-A', member: "foobar"};

if (instanceOfA(a)) {
    alert(a.member);
}
2 of 16
174

In TypeScript 1.6, user-defined type guard will do the job.

interface Foo {
    fooProperty: string;
}

interface Bar {
    barProperty: string;
}

function isFoo(object: any): object is Foo {
    return 'fooProperty' in object;
}

let object: Foo | Bar;

if (isFoo(object)) {
    // `object` has type `Foo`.
    object.fooProperty;
} else {
    // `object` has type `Bar`.
    object.barProperty;
}

And just as Joe Yang mentioned: since TypeScript 2.0, you can even take the advantage of tagged union type.

interface Foo {
    type: 'foo';
    fooProperty: string;
}

interface Bar {
    type: 'bar';
    barProperty: number;
}

let object: Foo | Bar;

// You will see errors if `strictNullChecks` is enabled.
if (object.type === 'foo') {
    // object has type `Foo`.
    object.fooProperty;
} else {
    // object has type `Bar`.
    object.barProperty;
}

And it works with switch too.

🌐
Reddit
reddit.com › r/typescript › can instanceof operator be used to check if an object is an instance of a n interface, or type?
r/typescript on Reddit: Can instanceOf operator be used to check if an object is an instance of a n interface, or type?
August 10, 2023 -

I'm learning through [roadmap](https://roadmap.sh/typescript) and got stuck here (screenshot) where it says instanceOf can be used to check if an object is an instance of interface or type. I tried to do in code but it gives error.

The given code is invalid in TypeScript:

interface Person {
    name: string;
    age: number
}

const person = {
    name: "Ken",
    age: 25
}

if (person instanceof Person) // Error: 'Person' only refers to a type, but is being used as a value here.

So am I using wrong? or that is a typo in that website? Any help would be highly appreciated. Thank!

Top answer
1 of 3
5
To add to what others have said already, there's a neat trick you can do in typescript to check if your instance is of a given "type". You declare it as an abstract class and implement the Symbol.hasInstance method. Example: abstract class Person { abstract readonly name: string; abstract readonly age: number; public static [Symbol.hasInstance](instance: unknown): instance is Person { if (instance === null || (typeof instance !== 'object' && !(instance instanceof Person))) return false; const name: unknown = (instance as any).name; const age: unknown = (instance as any).age; if (typeof name !== 'string' && !(name instanceof String)) return false; return typeof age === 'number' || age instanceof Number; } } Then you can use it as: const person = { name: "SomeName", age: 55 }; const noPerson = { weight: "300kg" }; console.log(person instanceof Person); // will print true console.log(noPerson instanceof Person); // will print false The advantage of this method in my opinion is that because typescript has a structure typing system, you can just do: class PersonImpl implements Person { constructor( readonly name: string, readonly age: number ) { } } console.log(new PersonImpl("SomeName", 55) instanceof Person); // will also print true This way, if you make a typo on PersonImpl you will know immediately that it's wrong and at runtime you can still type check.
2 of 3
5
You might be interested in type predicates . https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates
🌐
DEV Community
dev.to › worldpwn › typescript-instanceof-interface-is-it-possible-5flk
TypeScript 'instanceof' interface is it possible? - DEV Community
January 3, 2022 - Because types do not exist in runtime. There is no such thing as an interface in JavaScript. We can use string literal types in TypeScript to identify the interface.
🌐
GitHub
github.com › microsoft › TypeScript › issues › 58181
Proposal: Type-side use of `instanceof` keyword as an instance-query to allow instanceof checking · Issue #58181 · microsoft/TypeScript
April 13, 2024 - It follows that, for any instance query type type X = instanceof SomeClass, the intersection X & {} is always X. TypeScript considers classes with completely empty publicly declarad type structure as equivalent to any - although they might correspond to objects with rich but hidden functionality that need to be discriminated. This proposal would allow you to discriminate them. interface A1 {} interface A1Constructor { prototype: A1; new(): A1; } declare const A1: A1Constructor; interface A2 extends A1 {} interface A2Constructor { prototype: A2; new(): A2; } declare const A2: A2Constructor; declare let a1: instanceof A1; declare let a2: instanceof A2; const one = 1 as const; const sym = Symbol(); //////////////////////////////////////////////////////////////////// // compare to rhs without instanceof -- none of these are errors, which might not be desirable.
Author   craigphicks
🌐
HowToDoInJava
howtodoinjava.com › home › typescript › typescript instanceof with class, array and interface
TypeScript instanceof with Class, Array and Interface
April 15, 2024 - In TypeScript, the instanceof operator checking the type of an object at runtime. It determines whether an object is an instance of a particular class or constructor function. It returns true if the object is an instance of the checked type, ...
🌐
Tim Mousk
timmousk.com › blog › typescript-instanceof-interface
How To Use InstanceOf On An Interface In TypeScript? – Tim Mouskhelichvili
March 6, 2023 - Unfortunately, you cannot use the instanceOf keyword on an interface in TypeScript.
🌐
Learn TypeScript
learntypescript.dev › 07 › l4-instanceof-type-guard
Using an `instanceof` type guard | Learn TypeScript
instanceof is a JavaScript operator that can check whether an object belongs to a particular class. It also takes inheritance into account. ... The expression returns true or false depending on whether the object belongs to the class or not.
🌐
Medium
medium.com › @radekqwerty › typescript-how-to-check-that-argument-implements-interface-in-javascript-version-559e1bd2d83b
TypeScript: how to check that argument implements interface in JavaScript version | by Radek Anuszewski | Medium
March 22, 2017 - We used to use instanceof operator in JS code, we can’t do the same with TypeScript interfaces. But few days ago I read Looking at Abstract Classes and Methods in TypeScript article by Paul Galvin and it opened my eyes. For TypeScript code completion and compile-time checking, we use interfaces ...
Find elsewhere
🌐
EDUCBA
educba.com › home › software development › software development tutorials › typescript tutorial › typescript instanceof
TypeScript instanceof | Learn How instanceof works in TypeScript?
April 6, 2023 - Each argument value should be initialized with a separate variable type like “const” and creating a new object for the class using the “instanceof” operator; the class reference is validated and printed on the output console.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
TestMu AI Community
community.testmuai.com › ask a question
How to check if a variable implements an interface in TypeScript? - Ask a Question - TestMu AI Community
August 5, 2024 - For example: interface A { member: string; } var a: any = { member: "foobar" }; if (a instanceof A) alert(a.member); In TypeScript, instanceof does not work with interfaces, as they do not have a runtime representation.
🌐
Bobby Hadz
bobbyhadz.com › blog › typescript-instanceof-only-refers-to-type-but-is-being-used-as-value
(instanceof) 'X' Only refers to a type, but is being used as a value here | bobbyhadz
February 29, 2024 - The 'instanceof' error "only refers to a type, but is being used as a value here" occurs when we try to use the instanceof operator with a type instead of a value. To solve the error, create a class instead, or simply use a user-defined type guard.
🌐
GitHub
github.com › Microsoft › TypeScript › issues › 19120
use `instanceof` with a interface got compilation error · Issue #19120 · microsoft/TypeScript
October 12, 2017 - TypeScript Version: 2.5.3 Code export interface ISlicedTableData { origin: RawTableData; } if (tableData instanceof ISlicedTableData) { //
Author   rdkmaster
🌐
GeeksforGeeks
geeksforgeeks.org › typescript › typescript-instanceof-operator
TypeScript Instanceof Operator - GeeksforGeeks
July 22, 2024 - The TypeScript instanceof operator checks if an object is an instance of a specified class or constructor function at runtime.
🌐
DEV Community
dev.to › lico › typescript-checking-type-of-value-interface-and-type-4dn8
Typescript: Checking Type of a Value, (interface, type) - DEV Community
November 2, 2022 - const animals = [cat, dog, bird, cat, dog, bird]; console.log(instanceOf<Cat>(cat, "catId")); const cats = animals.filter((value) => instanceOf<Bird>(value, "birdId")); console.log("cats", cats);
🌐
LogRocket
blog.logrocket.com › home › how to use type guards in typescript
How to use type guards in TypeScript - LogRocket Blog
June 4, 2024 - The basic syntax for the instanceof type guard is below: ... interface Accessory { brand: string; } class Necklace implements Accessory{ kind: string; brand: string; constructor(brand: string, kind: string) { this.brand = brand; this.kind = kind; } } class bracelet implements Accessory{ brand: string; year: number; constructor(brand: string, year: number) { this.brand = brand; this.year = year; } } const getRandomAccessory = () =>{ return Math.random() < 0.5 ?
🌐
Edureka Community
edureka.co › home › community › categories › typesript › interface type check with typescript
Interface type check with Typescript | Edureka Community
May 31, 2022 - How to find out at runtime if a variable of type any implements an interface? interface A{ member ... offers a method implements. How can I use it ?
🌐
xjavascript
xjavascript.com › blog › typescript-instanceof-interface
Understanding `instanceof` in TypeScript with Interfaces — xjavascript.com
This will help other developers understand the code and use it correctly. In TypeScript, the instanceof operator cannot be used directly with interfaces because interfaces are a compile-time construct.