Typescript Class 使用接口作为类型而不是实现
Typescript Class use Interface as type instead of implement
我正在寻找模仿 using/implementing 接口的 C# 方式的方法。简而言之,我正在尝试复制以下代码:
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.";
}
}
使用工具效果很好,但我无法模仿 Class EBookReader 将电子书用作一种类型的方式。
codepen 和我的代码模型:http://codepen.io/Ornhoj/pen/gLMELX?editors=0012
using Ebook as a type
大小写敏感。
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。
我正在寻找模仿 using/implementing 接口的 C# 方式的方法。简而言之,我正在尝试复制以下代码:
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.";
}
}
使用工具效果很好,但我无法模仿 Class EBookReader 将电子书用作一种类型的方式。
codepen 和我的代码模型:http://codepen.io/Ornhoj/pen/gLMELX?editors=0012
using Ebook as a type
大小写敏感。
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。