Home > Enterprise >  Typescript interface clone
Typescript interface clone

Time:11-15

I declared an interface as below

interface Interface1 {
    property1: string;
    property2: string;
}

I have another interface Interface2 which needs to be the same as Interface1. I could have used Interface1 where ever Interface2 is used.

But I wanted to know if there is a way to clone Interface1 and assign it to Interface2

The way we do it for type declaration is as below.

type T1 = { property: 1 };
type T2 = T1;

I tried the below code.

interface Inteface2 extends Inteface1

The above line throws an error at the end of the line.

Parsing error: '{' expected .eslint

Is there a way to clone an interface and assign it to another interface?

CodePudding user response:

Initialize the interface

You should initialize an empty interface with empty brackets {}.

Typescript interface clone syntax

interface Inteface2 extends Inteface1{}

Now, Interface2 will have all the properties from Interface1.

Optionally you can add any properties to Interface2 in these brackets if needed.

interface Inteface2 extends Inteface1 {
  property3: string;
}

CodePudding user response:

Need to att trailing {}

interface Inteface2 extends Interface1{}

Playground

  • Related