S
S
Stockholm Syndrome2019-08-20 03:15:57
typescript
Stockholm Syndrome, 2019-08-20 03:15:57

How to merge an interface with a class if they are in different files?

if they are in the same file, then there is no problem

// a.ts 

interface A {
  f(m: 'string'): string;
  f(m: 'number'): number;
}

class A {
  f(m: string): any {
    // ...
  }
}

const a = new A(); 
a.f('string'); // returns string
a.f('number'); // returns number

but if you try to place them in different files and export the interface, the editor will complain about a name conflict
// a.ts 
interface A {
  f(m: 'string'): string;
  f(m: 'number'): number;
}

export default A;

// b.ts 
import A from './a'; // Import declaration conflicts with local declaration of 'A'.

class A {
  f(m: string): any {
    // ...
  }
}

I can declare a class with a different name that will implement the interface, but then I have to specify the type explicitly
class B implements A {
  f(m: string): any {
    // ...
  }
}

const a: A = new B(); 
a.f('string'); // returns string
a.f('number'); // returns number

Is it possible for me to exactly merge the interface with the class?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Shvets, 2019-08-20
@StockholmSyndrome

Take a look at this example, implementsdon't be fooled by the presence
https://www.typescriptlang.org/play/#code/JYOwLgpg
... type by the previous type merging their definitions. This is valid if the types are declared in the same module. And when you import from another module, this is an error.
this is true anyway, the variable gets the class by the name of the constructor. It's just that in the first case, interface A disappeared, only the class remained.
Read on the topic https://www.typescriptlang.org/docs/handbook/decla...
In general, in order to avoid confusion, you should not do this in live code, as you wrote above, make different names. And in ts there is no special need for this at all, implements is usually used to remember to implement the necessary methods.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question