classGreeter{ readonly name:string="world"; constructor(otherName?:stirng){ if(otherName!==undefined){ this.name=otherName; } } err(){ this.name="not ok"; // Cannot assign to 'name' because it is a read-only property. } }
classMyClass{ name = "MyClass"; getName = () => { returnthis.name; }; } const c = new MyClass(); const g = c.getName; // Prints "MyClass" instead of crashing console.log(g());
转为a.js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
var MyClass = /** @class */ (function () { functionMyClass() { var _this = this; this.name = "MyClass"; this.getName = function () { return _this.name; }; } return MyClass; }()); var c = new MyClass(); c.getName(); var g = c.getName; console.log(g());
classClearableBoxextendsBox{ clear() { this.contents = ""; } } const a = new ClearableBox(); const b = a.set("hello");
// const b: ClearableBox
下面这个例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classBox{ content: string = ""; sameAs(other: this) { return other.content === this.content; } } classDerivedBoxextendsBox{ otherContent: string = "?"; } const base = new Box(); const derived = new DerivedBox(); derived.sameAs(base); // Argument of type 'Box' is not assignable to parameter of type 'DerivedBox'. // Property 'otherContent' is missing in type 'Box' but required in type 'DerivedBox'.