我正在通过本书的工作雄辩的Javascript和我已经打了一个与章练习结束的障碍。我很早就决定,我将使用TypeScript主要是为了解决在vanilla JS之上的这些练习,只是为了让我自己了解TS提供给我的额外功能。TypeScript类继承构造函数混淆
充分行使可以在这里找到:http://eloquentjavascript.net/06_object.html#h_nLNNevzcF7
在我看来,我应该基本上延长已由本章中笔者,我已经做了我最好的定义预先存在的类在打字稿写入重新杠杆类:
//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类和继承,所以期待一些新手的错误。
你创造StretchCell的情况下,第一个参数是TextCell对象,你的超级正在期待一个字符串。在StretchCell你'构造函数(文字:any'是它的文字,或者是任何东西,因为你的超级(文字)期待一个字符串。?。 – Keith