TypeScript类继承构造函数混淆

Chr*_*odd 7 javascript oop inheritance class typescript

我正在阅读Eloquent Javascript这本书,我在章节结束时遇到了一些障碍.我很早就决定,我会主要使用TypeScript在vanilla JS之上解决这些练习,只是为了让自己接触到TS提供的额外功能.

完整的练习可以在这里找到:http://eloquentjavascript.net/06_object.html#h_nLNNevzcF7

在我看来,我本来应该扩展一个已经由本章作者定义的预先存在的类,我已经尽力在TypeScript中重写以利用类:

//from textbook.

function repeat(string: string, times: number): string {
    var result = '';
    for (var i = 0; i < times; i++)
        result += string;
    return result;
}

//inferred from textbook.

class TextCell {
    text: any;
    constructor(text: string) {
        this.text = text.split('');
    }
    minWidth(): number {
        return this.text.reduce((width: number, line: any) => Math.max(width, line.length), 0);
    }
    minHeight(): number {
        return this.text.length;
    }
    draw(width: number, height: number) : any[]{
        var result: any[] = [];
        for (var i = 0; i < height; i++) {
            var line = this.text[i] || '';
            result.push(line + repeat(' ', width - line.length));
        }
        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我对该课程的扩展:

class StretchCell extends TextCell {
    width:  number;
    height: number;
    constructor(text: any, width: number, height: number) {
        super(text);
        this.width  = width;
        this.height = height;
    }

    minWidth(): number {
        return Math.max(this.width, super.minWidth());
    }
    minHeight(): number {
        return Math.max(this.height, super.minHeight());
    }
    draw(width: number, height: number): any[] {
        return super.draw(this.width, this.height);
    }
}
Run Code Online (Sandbox Code Playgroud)

运行的'测试'是:

var sc = new StretchCell(new TextCell('abc'), 1, 2);

console.log(sc.minWidth());
// ? 3
console.log(sc.minHeight());
// ? 2
console.log(sc.draw(3, 2));
// ? ['abc', '   ']
Run Code Online (Sandbox Code Playgroud)

我根本没有得到任何输出,而是我得到:TypeError: text.split is not a function.我知道我收到此错误是因为我试图在除字符串以外的类型上调用.split(),但我不确定我的代码中哪个text被强制转换为其他类型并导致此错误被抛出

我怀疑我的问题在于班级的构造者,但我不清楚.任何洞察我的代码的组成将不胜感激.这也是我第一次使用TypeScript类和继承,所以期待一些新手的错误.

art*_*tem 7

此代码在扩展类构造函数中

constructor(text: any, width: number, height: number) {
    super(text);
Run Code Online (Sandbox Code Playgroud)

通过text调用直接传递给预先存在的类构造函数super(text).所以text这里应该是一个字符串,因为它是如何在预先存在的TextCell构造函数中声明的.

但是当您创建StretchCell类的实例时,您TextCell将为text参数传递对象实例,而不是字符串.这是text.split is not a function错误的原因- TextCell没有调用方法split.

扩展类构造函数应声明为

constructor(text: string, width: number, height: number) {
    super(text);
Run Code Online (Sandbox Code Playgroud)

并且StretchCell必须像这样创建实例:

var sc = new StretchCell('abc', 1, 2);
Run Code Online (Sandbox Code Playgroud)