3 回答

TA貢獻1869條經驗 獲得超4個贊
它是 JavaScript 的嚴格語法超集,并為語言添加了可選的靜態類型
另一件需要注意的是,像非強類型的特性或類似的東西在 TypeScript 中不起作用,這種現象與它類似。

TA貢獻2051條經驗 獲得超10個贊
以下是TS解釋的流程。
所有屬性、方法都被初始化。
然后在實例化過程中,調用構造函數并使用默認值設置上述屬性。
在您的代碼中:
class Rectangle {
constructor(height:number, width:number) {
this.height = height; //error
this.width = width; //error
}
}
沒有提到任何屬性,因此您會收到錯誤消息

TA貢獻1798條經驗 獲得超7個贊
您可以這樣做,但是您當然會與該語言的類型檢查功能作斗爭。
class Rectangle {
constructor(height:number, width:number) {
(this as any).height = height;
(this as any).width = width;
}
}
const rt = new Rectangle(100, 200);
console.log((rt as any).width);
也就是說,如果您轉換為 any,您可以像在純 JavaScript 中那樣做任何事情。
添加回答
舉報