TypeScript类继承构造函数混淆

TypeScript class inheritance constructor confusion

本文关键字:构造函数 继承 TypeScript      更新时间:2023-09-26

我正在阅读《雄辩的Javascript》这本书,我在章节末尾的练习中遇到了一点障碍。我很早就决定,我将主要使用TypeScript在普通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;
    }
}

这是我对这个类的扩展:

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

运行的"测试"如下:

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', '   ']

我目前没有得到任何输出,而是得到:TypeError: text.split is not a function。我知道我得到这个错误,因为我试图调用。split()上的类型,而不是一个字符串,但我不确定在我的代码中,text被强制成不同的类型,并导致这个错误被抛出。

我有一种偷偷摸摸的怀疑,我的问题在于类的构造函数,但我不清楚。如果您对我的代码的组成有任何深入的了解,我将不胜感激。这也是我第一次使用TypeScript类和继承,所以可能会出现一些新手错误。

扩展类构造函数

constructor(text: any, width: number, height: number) {
    super(text);

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

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

扩展类构造函数应该声明为

constructor(text: string, width: number, height: number) {
    super(text);

StretchCell实例必须这样创建:

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