【问题标题】:Typescript Class use Interface as type instead of implementTypescript 类使用接口作为类型而不是实现
【发布时间】:2016-11-16 06:40:20
【问题描述】:

我正在寻找一种方法来模仿 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 使用 Ebook 作为类型的方式。

用我的代码模型编写代码:http://codepen.io/Ornhoj/pen/gLMELX?editors=0012

【问题讨论】:

    标签: javascript typescript interface es6-class


    【解决方案1】:

    使用电子书作为类型

    区分大小写。

    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

    【讨论】:

    • 喜欢它,因为它是一个简单的区分大小写的错误,让我在一天半的时间里一直处于困境。 +1 并给出正确答案。
    猜你喜欢
    • 2019-06-27
    • 1970-01-01
    • 1970-01-01
    • 2020-06-04
    • 1970-01-01
    • 2020-04-17
    • 2021-10-29
    • 2020-01-10
    • 2021-02-21
    相关资源
    最近更新 更多