2016-11-16 104 views
0

我正在寻找模仿C#使用/实现接口的方式。总之,我试图复制下面的代码:Typescript类使用接口作为类型而不是实现

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."; 
    } 
} 

使用机具工作正常,但是我不能模拟天生使用电子书作为一种类型的类EBookReader方式。

codepen我的代码样机:http://codepen.io/Ornhoj/pen/gLMELX?editors=0012

回答

2

使用电子书作为一种类型

的情况是敏感。

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(); 

测试此代码in the playground

+0

当它是一个简单的区分大小写的错误,让我在一天半的时间内就爱上它。 +1并给出正确答案。 –

相关问题