2 回答

TA貢獻1784條經驗 獲得超2個贊
您正在嘗試像運行 JavaScript 一樣運行 TypeScript 文件。JavaScript 和 TypeScript 不一樣,node
只能理解 JavaScript,不能理解 TypeScript。
您需要安裝軟件包typescript
和ts-node
. 您可以在全局范圍內這樣做,以便您可以在任何地方使用它,用于單個文件:
npm i -g typescript ts-node
之后,您可以使用ts-node
而不是node
運行您的文件:
ts-node myScript.ts
這會將您的 TypeScript 文件即時編譯為 JavaScript 并node
為您運行結果。

TA貢獻1784條經驗 獲得超7個贊
我很確定要么存在格式問題,要么您使用的編譯器不喜歡語法,但這是我在 https://www.typescriptlang.org/play/中執行的代碼 ,它工作得非常好。
class Point {
private x: number;
private y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
public distance(otherPoint: Point): number {
return Math.sqrt(
Math.pow(this.x - otherPoint.getX(), 2) +
Math.pow(this.y - otherPoint.getY(), 2));
}
public getX() {
return this.x;
}
public getY() {
return this.y;
}
}
class Circle {
private center: Point;
private radius: number;
constructor(center: Point, radius: number) {
this.radius = radius;
this.center = center;
}
public isInside(otherPoint: Point): boolean {
return this.center.distance(otherPoint) < this.radius;
}
}
class Triangle extends Point {
private z: number;
constructor(x:number, y: number, z: number) {
super(x, y);
this.z = z;
}
public getZ() {
return this.z
}
public getPerimeter(otherPoint: Triangle): number {
return otherPoint.getX() + otherPoint.getY() + otherPoint.getZ()
}
}
let per = new Triangle(24, 61, 32);
console.log(per);
在我提到的鏈接中運行上面的代碼,點擊“運行”并點擊“F12”打開控制臺,你會看到console.log的輸出
添加回答
舉報