Rudi Ørnhøj Rudi Ørnhøj - 25 days ago 6
Javascript Question

Typescript Class use Interface as type instead of implement

I'm looking for at way to mimick the C# way of using/implementing Interfaces. In short I'm trying to replicate the following code:

interface EBook {
function read();
}

class EBookReader {

private $book;

function __construct(EBook $book) {
$this->book = $book;
}

function read() {
return $this->book->read();
}

}

class PDFBook implements EBook {

function read() {
return "reading a pdf book.";
}
}

class MobiBook implements EBook {

function read() {
return "reading a mobi book.";
}
}


Using implements works fine however I cannot mimick the Class EBookReader way of using Ebook as a type.

codepen with my code mockup: http://codepen.io/Ornhoj/pen/gLMELX?editors=0012

Answer

using Ebook as a type

The case is sensitive.

interface IEBook {
    read();
}

class EBookReader {
    book: IEBook;

    constructor(book: IEBook) {
        this.book = book;
    }

    read() {
        this.book.read();
    }

}

class PDFBook implements IEBook {
    read() {
        console.log("reading a pdf book.");
    }
}

class MobiBook implements IEBook {
    read() {
        console.log("reading a mobi book.");
    }
}
var pdf = new PDFBook();
var reader = new EBookReader(pdf);
reader.read();

Test this code in the playground.