Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extends and implements in one class in TypeScript

Can I do this in TypeScript?

export interface IMyInterface {   doSomething(): void; }  export class MyBaseClass {   myBaseClassHasProperty: string;    constructor(){     this.myBaseClassHasProperty = 'some value';   }   myBaseClassHasMethods(): void {     console.log(this.myBaseClassHasProperty);   } }  export class MyClass extends MyBaseClass implements IMyInterface {   constructor() {     super();   }    doSomething(): void {     this.myBaseClassHasMethods();   } } 

In runtime it throws:

Uncaught ReferenceError: MyBaseClass is not defined

like image 537
Everton Santos Avatar asked Mar 30 '15 00:03

Everton Santos


People also ask

Can a class extend and implement at the same time TypeScript?

In TypeScript, interfaces can also extend classes, but only in a way that involves inheritance. When an interface extends a class, the interface includes all class members (public and private), but without the class' implementations.

Can a class extends and implements at the same time?

Note: A class can extend a class and can implement any number of interfaces simultaneously.

What is the difference between implements and extends in TypeScript?

Today, a friend ask about the difference between extends and implements . The short answer for him was: extends: The class get all these methods and properties from the parent, so you don't have to implement. implements: The class has to implement methods and properties.

Can a TypeScript class implement multiple interfaces?

Typescript allows an interface to inherit from multiple interfaces. Use the extends keyword to implement inheritance among interfaces.


1 Answers

in runtime i get this Uncaught ReferenceError: MyBaseClass is not defined

Yes you can do that. The code you posted will work fine.

However I suspect in your actual code you have it split across multiple files and MyBaseClass is not executed before the code for MyClass.

Fix JavaScript ordering or use external modules to have the ordering determined by the module loader.

like image 119
basarat Avatar answered Oct 02 '22 14:10

basarat