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.

Discussions

Can a TypeScript type implement an interface? - Stack Overflow
I'm learning TypeScript and I want to extend a type with an interface, I've found a blog post which suggests that it's not possible for a type to extend/implement interfaces. Here is a code example... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How can I create an object based on an interface file definition in TypeScript? - Stack Overflow
I have defined an interface like this: interface IModal { content: string; form: string; href: string; $form: JQuery; $message: JQuery; $modal: JQuery; $submits: JQuery... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Casting an object to an interface it "doesn't" implement?
Short answer is: that's just the way it works in a strongly typed language. You can't cast an object to an interface that it doesn't explicitly implement. As to how to get around this, create a DogWrapper and a CatWrapper. The dog wrapper would look like class DogWrapper : IPet { private Dog dog; public DogWrapper(Dog dog) { this.dog = dog; } public string Ears { get { return dog.Ears; } set { dog.Ears = value; } } public string Fur { get { return dog.Fur; } set { dog.Fur = value; } } } You would create a similar CatWrapper. Then you can use: Console.WriteLine((new DogWrapper(new Dog()) as IPet).Fur) More on reddit.com
๐ŸŒ r/csharp
80
31
December 3, 2023
Can instanceOf operator be used to check if an object is an instance of a n interface, or type?
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. More on reddit.com
๐ŸŒ r/typescript
10
5
August 10, 2023
People also ask

What is a TypeScript interface?
A TypeScript interface is how we can define the structure of an object by specifying the properties and methods that are on the object. Theyโ€™re primarily used for type-checking.
๐ŸŒ
prismic.io
prismic.io โ€บ blog โ€บ typescript-interfaces
TypeScript Interfaces: A Practical Guide with Code Examples
What are the types of TypeScript interfaces?
While there arenโ€™t different types of interfaces, they can be used in various different ways, such as function types, object types, optional properties, index signatures, and more.
๐ŸŒ
prismic.io
prismic.io โ€บ blog โ€บ typescript-interfaces
TypeScript Interfaces: A Practical Guide with Code Examples
When should I use interfaces in TypeScript?
Youโ€™ll use interfaces in various places in TypeScript, but most commonly, when you want to define the structure of an object and ensure type safety.
๐ŸŒ
prismic.io
prismic.io โ€บ blog โ€บ typescript-interfaces
TypeScript Interfaces: A Practical Guide with Code Examples
๐ŸŒ
Prismic
prismic.io โ€บ blog โ€บ typescript-interfaces
TypeScript Interfaces: A Practical Guide with Code Examples
September 28, 2023 - In this example, we have an interface called PersonInt and use the implements keyword to say the class Person will have all of the types defined in PersonInt. Because this isnโ€™t true and the age field is missing in the class, an error is thrown. When working with objects in TypeScript, itโ€™s ...
๐ŸŒ
Codecademy
codecademy.com โ€บ learn โ€บ learn-typescript โ€บ modules โ€บ learn-typescript-advanced-object-types โ€บ cheatsheet
Learn TypeScript: Advanced Object Types Cheatsheet | Codecademy
Interface is useful in typing objects written for object-oriented programs. ... To apply a TypeScript interface to a class, add the implements keyword after the class name followed by the interface name.
๐ŸŒ
Tutorial Teacher
tutorialsteacher.com โ€บ typescript โ€บ typescript-interface
TypeScript Interfaces
So, objects of IEmployee must include all the properties and methods of the IPerson interface otherwise, the compiler will show an error. Similar to languages like Java and C#, interfaces in TypeScript can be implemented with a Class.
๐ŸŒ
Strapi
strapi.io โ€บ blog โ€บ typescript-interfaces
What Are Typescript Interfaces and How Do They Work?
Interfaces in TypeScript serve as powerful contracts that define the shape of an object. They allow you to specify what properties and methods an object must include, without dictating implementation details.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ how-typescript-interfaces-work
How TypeScript Interfaces Work โ€“ Explained with Examples
February 23, 2024 - At its core, an interface in TypeScript is a syntactical contract that defines the expected structure of an object. It provides a way to describe the shape of objects, including their properties and methods, without implementing any functionality.
Find elsewhere
๐ŸŒ
Educative
educative.io โ€บ blog โ€บ typescript-interfaces
A Simple Guide to Typescript Interfaces: declaration & use cases
March 10, 2026 - Declaring InterfacesInterface vs ... about TypeScript ... A TypeScript interface is an abstract type that defines the shape of an object by specifying property names, value types, and method signatures the compiler will enforce....
๐ŸŒ
Bobby Hadz
bobbyhadz.com โ€บ blog โ€บ typescript-check-if-object-implements-interface
Check if an Object implements an interface in TypeScript | bobbyhadz
Copied!interface Employee { id: ... Hadz" console.log(emp.salary); // ๐Ÿ‘‰๏ธ 100 } ... We used a user-defined type guard to check if an object implements an interface....
๐ŸŒ
Medium
abhishekw.medium.com โ€บ typescript-how-to-create-and-use-a-interface-6fcf6200b55b
TypeScript: How to Create and Use a Interface | by Abhishek Wadalkar | Medium
January 22, 2025 - Typescript interfaces are a key feature that allows you to define the structure of an object, ensuring type safety in your application. Interfaces can describe properties, methods, and their expected types, making your code robust and ...
๐ŸŒ
LogRocket
blog.logrocket.com โ€บ home โ€บ understanding and using interfaces in typescript
Understanding and using interfaces in TypeScript - LogRocket Blog
October 17, 2024 - The Dog and Cat classes implement the Animal interface, ensuring they have the necessary properties and methods for functions that accept an Animal argument. The playWithAnimal function demonstrates duck typing. It doesnโ€™t check the specific class of the animal parameter โ€” it only checks if the object has the name property and the makeSound() method.
๐ŸŒ
Technical Feeder
technicalfeeder.com โ€บ 2021 โ€บ 02 โ€บ how-to-check-if-a-object-implements-an-interface-in-typescript
How to check if an object implements an interface in Typescript | Technical Feeder
May 4, 2023 - If two interfaces have the same properties but one of the data types is different, we somehow need to differentiate them. In this case, typeof needs to be used to check the data type. However, if the data type is unknown type, we canโ€™t access the property. The following post shows how to solve the problem. Object Type Check By User Defined Type Guard with Record Type
๐ŸŒ
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 - In code above Null Object design pattern is used, it helps to avoid checking if object is None before calling action on it. And it looks pretty much the same like in Python, we define prototype which other prototypes can extend: /** * * @interface */ function Device(){}Device.prototype.getName = function( throw new Error('Not implemented!'); );DeviceImpl.prototype = Object.create(Device.Prototype);/** * * @implements Device */ function DeviceImpl(){ Device.call(this); }// Somewhere in code if ( !(device instanceof Device) ) { throw new TypeError('Bad interface!'); }
๐ŸŒ
DEV Community
dev.to โ€บ khush2706 โ€บ interfaces-in-typescript-l0h
Interfaces in TypeScript - DEV Community
July 17, 2022 - That is, that class will have to implement all the properties and methods in that interface along with their types. An interface acts as a contract with our application. It states what needs to be done but doesn't specify how it will be done. Further we cannot instantiate an interface. It can only be referenced by the class object that implements it.
Top answer
1 of 2
4

The answer to the question as asked is no, you cannot do this directly with a type alias. An implements clause only applies to class declarations, and an extends clause only applies to interface or class declarations.

Of course it is easy enough to get analogous functionality:


An implements clause on a class just checks to see if the class instance is assignable to the declared type, and produces a compiler warning if it's not; it has no effect on the type of the instance. You can do the same thing with a utility type like

type Implements<T, U extends T> = U

So Implements<T, U> doesn't have an effect on the resulting type, U, but since U is constrained to T, you will get a warning if it is not assignable.

Let's test it:

type Cat = Implements<IPet, {
    needsFood: boolean,
    color: string,
}> // okay

type Dog = Implements<IPet, {
    bark(): void 
}>; // error!  Property 'needsFood' is missing in type '{ bark(): void; }'

Looks good.


Meanwhile an extends clause can be used to add members to or narrow members of a parent type. This is essentially the same as an intersection type, and so we can make a utility type to capture this:

type Extends<T, U extends Pick<T, keyof T & keyof U>> =
    T & U;

Here we combine both the parent type T and the new members U. I've constrained U to make sure that you can't add conflicting properties, which is similar to what happens if you try to extend an interface with conflicting properties:

type Cat2 = Extends<IPet, {
    color: string
}>

type Dog2 = Extends<IPet, {
    needsFood: number // error! 
}>; // error! 
// Type '{ needsFood: number; }' does not satisfy the constraint Pick<IPet, "needsFood">.

Also looks good.


Those approaches aren't completely identical to implements/extends clauses, but they should be close enough for a lot of use cases. There are almost surely edge cases where they differ and it's possible these could be repaired or worked around. But the basic takeaway here is that you can use generic constraints and intersection types to build a solution.

Playground link to code

2 of 2
2

In TypeScript, you can indeed extend a type with an interface. The syntax for extending a type with an interface is using the extends keyword. Here's an example:


interface Shape {
  color: string;
}

type Square = Shape & {
  sideLength: number;
}

let square: Square = {
  color: "blue",
  sideLength: 10
};

This creates a new type Square that extends the Shape interface with an additional property sideLength. You can also use interfaces with classes for defining the shape of the instances of the class. Classes in TypeScript can implement interfaces to enforce that the class meets the structure defined by the interface.

So, you can use both types and classes to work with interfaces in TypeScript.

๐ŸŒ
Bobby Hadz
bobbyhadz.com โ€บ blog โ€บ typescript-class-implement-interface
Class implementing Interfaces in TypeScript | bobbyhadz
February 29, 2024 - The Developer class correctly implements the Employee interface because the name property is not required, however, the property doesn't automatically get assigned on the class. I've also written an article on how to check if an object implements an interface.
Top answer
1 of 16
762

If you are creating the "modal" variable elsewhere, and want to tell TypeScript it will all be done, you would use:

declare const modal: IModal;

If you want to create a variable that will actually be an instance of IModal in TypeScript you will need to define it fully.

const modal: IModal = {
    content: '',
    form: '',
    href: '',
    $form: null,
    $message: null,
    $modal: null,
    $submits: null
};

Or lie, with a type assertion, but you'll lost type safety as you will now get undefined in unexpected places, and possibly runtime errors, when accessing modal.content and so on (properties that the contract says will be there).

const modal = {} as IModal;

Example Class

class Modal implements IModal {
    content: string;
    form: string;
    href: string;
    $form: JQuery;
    $message: JQuery;
    $modal: JQuery;
    $submits: JQuery;
}

const modal = new Modal();

You may think "hey that's really a duplication of the interface" - and you are correct. If the Modal class is the only implementation of the IModal interface you may want to delete the interface altogether and use...

const modal: Modal = new Modal();

Rather than

const modal: IModal = new Modal();
2 of 16
284

If you want an empty object of an interface, you can do just:

var modal = <IModal>{};

The advantage of using interfaces in lieu of classes for structuring data is that if you don't have any methods on the class, it will show in compiled JS as an empty method. Example:

class TestClass {
    a: number;
    b: string;
    c: boolean;
}

compiles into

var TestClass = (function () {
    function TestClass() {
    }
    return TestClass;
})();

which carries no value. Interfaces, on the other hand, don't show up in JS at all while still providing the benefits of data structuring and type checking.

๐ŸŒ
GitBook
basarat.gitbook.io โ€บ typescript โ€บ type-system โ€บ interfaces
Interfaces | TypeScript Deep Dive
// Lib a.d.ts interface Point { x: number; y: number; } declare var myPoint: Point; // Lib b.d.ts interface Point { z: number; } // Your code var myPoint.z; // Allowed!
๐ŸŒ
TheServerSide
theserverside.com โ€บ blog โ€บ Coffee-Talk-Java-News-Stories-and-Opinions โ€บ How-to-program-to-an-interface-in-TypeScript
How to program to an interface in TypeScript
In other words, an interface declares what a class is supposed to do in terms of properties and methods, but not how the properties and methods work. Rather, a class implements the behavior an interface represents. The following is an example of an interface programming in TypeScript named IAnimal.
๐ŸŒ
DEV Community
dev.to โ€บ aneeqakhan โ€บ how-to-create-interfaces-in-typescript-24gp
How to create interfaces in TypeScript - DEV Community
March 18, 2022 - Now newEmployee2 have one additional property teamName but it still inherits the Employee interface because as long as an object has all the required properties of an interface can inherit/extends an interface. This is also called a Structural Type System. We can also declare optional members of the interface just like we did in optional params in a function. interface Person { firstName: string; lastName: string; midName?: string; } While implementing an interface, we can skip optional members of an interface, and the compiler won't give any error.