Home > database >  export removes interface implementation from class in typeScript
export removes interface implementation from class in typeScript

Time:03-03

I have .ts file with class declaration and .d.ts file with interface declaration.

.ts file example:

class A {
  constructor() {
    this.name = "Jo";
  }
}

.d.ts file example:

interface A {
  name: string
}

So, the problem is - everything working fine, class A auto detect interface A and implements it.

But, when i add class named export or default export, like in example below - interface implementation disappearing, it's again clear class A.

export default class A {
  constructor() {
    this.name = "Jo";
  }
}

or

class A {
  constructor() {
    this.name = "Jo";
  }
}
export { A }

Both variants leads to same problem - "Property 'name' does not exist on type 'A'".

If add interface to same file it will works, but i need this interface for global using and don't want to write same implementation directly in the class or same file.

So, what is going on and what should i do to make things right?

CodePudding user response:

It's most unusual to write your interfaces in .d.ts files and to collide properties with a same-named class.

The idiomatic was to do this is to write the interface in one file:

export interface Nameable{
    name: string
}

and import it in another and use it correctly via the implements keyword:

import {Nameable} from './Nameable';

export class A implements Nameable{
    // etc
}

You can, of course, import the very same interface into any other file. Making things global rarely works out for the best.

CodePudding user response:

When I put your code on a typescript playground I get this error:

class A Merged declaration 'A' cannot include a default export declaration. Consider adding a separate 'export default A' declaration instead.(2652)

And if you follow that advice:

interface A {
  name: string
}

class A {
  constructor() {
    this.name = "Jo";
  }
}

export default A

It works as you expect Playground


However, if the file that class A is in is Typescript, then you don't need the .d.ts file at all and you class should just be:

class A {
  name: string
  constructor() {
    this.name = "Jo";
  }
}

Which is it's own interface implicitly:

const a: A = { name: 'Foo' } // fine

Playground

  • Related