简体   繁体   中英

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM