0

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Love it when it's a simple case-sensitive error which has kept me at bay for one-and-a-half day. +1 and correct answer given.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.