Typescript interface extends class

Extend Interface in TypeScript

We can extend the Interfaces in TypeScript to include other interfaces. This helps us to create a new interface consisting of definitions from the other interfaces. Extending interfaces gives us more flexibility in how we define our interfaces and reuse the existing interfaces.

Extending Interface

We extend an interface by using the extends keyword after the interface and name followed by a list of interfaces each separated by a comma.

This example Employee interface extends the Address interface. The employee object must contain all the properties from both the interface.

You can extend an interface from several other interfaces.

In this example, both Customer and Employee Interface extends the Person interface which in turn extends an Address interface.

Common Properties are merged

If the Interface and the extended interfaces contain a common property, then their data type must be compatible with each other. In such cases they are merged else the compiler throws an error.

The BetterProduct extends the Product interface. Both the Interfaces contain a common property id . Since the data type matches, the compiler merges both together and does not complain.

Читайте также:  Html img link to file

But if you change the data type ( id is a string in BetterProduct interface) as in this example, the compiler throws the error.

Note that data types need not be the same. But they must be compatible with each other. In the example below the id property has number and any data types. Since they are compatible with each other compiler does not complain.

This example has id property with unknown type & number data type. The number can be assigned to an unknown data type. Since the BetterProduct extends id from unknown to a number this code is acceptable.

But unknown cannot be assigned to a number data type. Hence BetterProduct cannot extend the number to an unknown type. This code throws an error.

Common functions are merged if the signature is Compatible

Similar to the properties, the functions with the same name are merged only if they have compatible signatures. If the function signatures are not compatible then they are not merged and the compiler will throw an error.

Readonly Properties

The extended interfaces can override the readonly and optional properties.

This example defines a read-only name property in the Person Interface. The Customer interface extends it and also declares the name property without the readonly modifier. This allows us the modify the name property on any object which is created from the Customer Interface.

The employee interface does not override the name property. Typescript compiler throws an error if any object created from the Employee Interface tries to modify the name property.

Interfaces Extending Classes

An Interface can also extend classes. The extended interface will include all class members (both public and private) but without any implementation.

In this example, the Employee extends the Person class and adds a new property Designation . The newly created employee must contain the name property which is from the Person class along with the Designation

If the class contains a function, its implementation is not copied. The object created using the interface must provide its own implementation. The employee object in the following example must implement the printName function from the Person class although the class contains its implementation.

Extending the class has one significant restriction. If the class from which we extend has private property (or protected property), then we can use the interface only with those classes which extend the class that the interface has extended.

For Example, we have added a private property ( id ) to the Person class. The IEmployee interface extends the Person class. But when we create a new object employee from the interface IEmployee the compiler will throw the error.

If we do not add the id property to the employee object, the compiler complains that the Property ‘id’ is missing in type’ employee. But if we add the id property, it still complains because the id is a private property adding it to the employee object makes it public property.

Hence, the only way you can use it is to create a new class that extends the class (or subclasses of that class) from which the interface extends.

For Example, the IEmployee interface extends the class Person , which has private property. We can use the IEmployee interface only on those classes which extend from the Person class (or any subclass of Person class).

Источник

How To Extend An Interface In TypeScript?

Tim Mouskhelichvili

When working on a TypeScript project, a developer sometimes needs to modify an existing interface by adding one or more members. Luckily, this is easy to do.

To extend an interface in TypeScript, you must use the extends keyword.

This article explains using the extends keyword in TypeScript and shows many code examples.

typescript extend interface

How to make an interface extend another interface?

To extend an interface, a developer must use the extends keyword.

Let’s see how it works with an example.

We have an interface containing two methods, AND we want to add another function WITHOUT modifying the original one.

typescriptinterface IAnimal < eat: (food: string) => void; sleep: () => void; > interface IFish extends IAnimal < swim: () => void; > const obj: IFish = < eat: (food: string): void => < console.log('Eating ' + food); >, sleep: (): void => < console.log('Sleeping'); >, swim: (): void => < console.log('Swimming'); > >

We first define the IAnimal interface, which contains two methods.

Then we define the IFish interface, which extends the IAnimal interface and adds a new method.

The IFish interface contains the eat, sleep, and swim functions.

Note: If you are interested in extending a type, I wrote an extensive guide.

How to extend multiple interfaces?

In TypeScript, an interface can extend multiple interfaces.

Use the extends keyword and pass a list of comma-separated interfaces.

Let’s see how it works with an example.

typescriptinterface IAnimal < eat: (food: string) => void; sleep: () => void; > interface IFish < swim: () => void; > interface IJellyFish extends IAnimal, IFish < glow: () => void; > const obj: IJellyFish = < eat: (food: string): void => < console.log('Eating ' + food); >, glow: (): void => < console.log('Glowing'); >, sleep: (): void => < console.log('Sleeping'); >, swim: (): void => < console.log('Swimming'); > >;

In this example, the IJellyFish interface extends the IAnimal and the IFish interfaces.

The best Web Development course in 2023! 👉 Learn Web Development

How to make an interface extend a class?

TypeScript gives developers the ability to make an interface extend a class.

The interface inherits the methods and properties from the class it extends.

Protected and private members are also inherited, making the interface only implementable by a class containing those protected and private members.

Let’s see how it works with an example.

typescriptclass Animal < public name: string = ''; > interface IFish extends Animal < swim: () => void; > const fish: IFish = < name: 'Fish', swim: (): void => < console.log('swim'); > >;

In this example, the IFish interface inherits the name property from the Animal class.

How to override a property’s type when extending an interface?

To override a property’s type when extending an interface, you can use the omit utility type.

Let’s see how to do it with an example.

typescriptinterface IOriginal < name: string > interface IFinal extends Omit < name: number > const obj: IFinal = < name: 222 >;

In this example, we override the name property’s type from string to number.

Final thoughts

As you can see, extending an interface is simple in TypeScript.

Simply use the extends keyword, and voila!

typescript extend interface

Here are some other TypeScript tutorials for you to enjoy:

The best Web Development course in 2023! 👉 Learn Web Development

Tim Mouskhelichvili

Hello! I am Tim Mouskhelichvili, a Freelance Developer & Consultant from Montreal, Canada. I specialize in React, Node.js & TypeScript application development. If you need help on a project, please reach out, and let’s work together.

Источник

How to Extend Interfaces in TypeScript

Summary: in this tutorial, you will learn how to extend an interface that allows you to copy properties and methods of one interface to another.

Interfaces extending one interface

Suppose that you have an interface called Mailable that contains two methods called send() and queue() as follows:

interface Mailable < send(email: string): boolean queue(email: string): boolean >Code language: TypeScript (typescript)

And you have many classes that already implemented the Mailable interface.

Now, you want to add a new method to the Mailable interface that sends an email later like this:

later(email: string, after: number): voidCode language: TypeScript (typescript)

However, adding the later() method to the Mailable interface would break the current code.

To avoid this, you can create a new interface that extends the Mailable interface:

interface FutureMailable extends Mailable < later(email: string, after: number): boolean >Code language: TypeScript (typescript)

To extend an interface, you use the extends keyword with the following syntax:

interface A < a(): void > interface B extends A < b(): void > Code language: TypeScript (typescript)

The interface B extends the interface A , which then have both methods a() and b() .

Like classes, the FutureMailable interface inherits the send() and queue() methods from the Mailable interface.

The following shows how to implement the FutureMailable interface:

class Mail implements FutureMailable < later(email: string, after: number): boolean < console.log(`Send email to $ in $ ms.`); return true; > send(email: string): boolean < console.log(`Sent email to $ after $ ms. `); return true; > queue(email: string): boolean < console.log(`Queue an email to $ .`); return true; > >Code language: TypeScript (typescript)

Interfaces extending multiple interfaces

An interface can extend multiple interfaces, creating a combination of all the interfaces. For example:

interface C < c(): void > interface D extends B, C < d(): void > Code language: TypeScript (typescript)

In this example, the interface D extends the interfaces B and C . So D has all the methods of B and C interfaces, which are a() , b() , and c() methods.

Interfaces extending classes

TypeScript allows an interface to extend a class. In this case, the interface inherits the properties and methods of the class. Also, the interface can inherit the private and protected members of the class, not just the public members.

It means that when an interface extends a class with private or protected members, the interface can only be implemented by that class or subclasses of that class from which the interface extends.

By doing this, you restrict the usage of the interface to only class or subclasses of the class from which the interface extends. If you attempt to implement the interface from a class that is not a subclass of the class that the interface inherited, you’ll get an error. For example:

class Control < private state: boolean; > interface StatefulControl extends Control  < enable(): void >class Button extends Control implements StatefulControl  < enable() < >> class TextBox extends Control implements StatefulControl  < enable() < >> class Label extends Control  < >// Error: cannot implement class Chart implements StatefulControl  < enable() < >>Code language: PHP (php)

Summary

  • An interface can extend one or multiple existing interfaces.
  • An interface also can extend a class. If the class contains private or protected members, the interface can only be implemented by the class or subclasses of that class.

Источник

Оцените статью