Alexander Zeitler
Alexander Zeitler

Reputation: 13089

Extending a TypeScript interface from JavaScript: TypeError: Class extends value undefined is not a function or null

I've a TypeScript interface like this:

export interface Foo {
  bar: string
}

This will compile down to an empty .js file. So when using the TypeScript interface in an ES6 Node module, I'll get this error:

TypeError: Class extends value undefined is not a function or null

A workaround will be to create a class

export class BaseFoo {
  bar: string
}

Now I can use BaseFoo from ES6 without getting the aforementioned error. So it is not possible to just have interfaces in TypeScript with ES6 interop or is there an more elegant way than having Base* classes (which are not really base classes in the end) here?

Update: I understand the different concepts behind interfaces and base classes but my questions is about a best practice how to create a library in TypeScript which uses interfaces and how to build it in a way plain ES6 (which does not have interfaces) can also consume this library.

Upvotes: 1

Views: 1244

Answers (2)

llgcode
llgcode

Reputation: 113

You may want to use this @implements jsdoc annotation:

/** @implements {Print} */
class TextBook {
  print() {
    // TODO
  }
}

Upvotes: 0

Jacques
Jacques

Reputation: 3774

I think you my be misunderstanding how to properly use an interface. Interfaces are not "Base" objects, they simple define what an object should look like.

In typescript, many times an interface is used as a type for an object, but in general can be used to define what a class should "look like" as well.

For instance:

interface Foo {
  bar: string;
  baz: number;
  bang(): void;
}

In this case, any object/class that implements Foo will need to have these three things.

IE:

class FooImplemented implements Foo {
  bar = 'Hello World';
  baz = 42;

  bang() {
    print(this.bar);
  }
}

If I do not define bar, baz and/or bang; typescript will throw an error at compile time that I'm not properly implementing the Foo interface in the FooImplemented class.

To summarize, an interface tells the compiler what something is supposed to look like. And an interface can extend another interface. However, a class cannot extend an interface, but it can implement one. (Or multiple)

Check out the docs on interfaces on typescripts website.

Upvotes: 2

Related Questions