class User { constructor(private _name: string){ } public sayHi(): void { console.log("hi i am" + this._name); } get name(){ return this._name; } set name(newValue: string){ this._name = newValue; } } var tom = new User("Tom"); console.log(tom.name); tom.sayHi(); console.log(tom.name); tom.sayHi();
class User { constructor(protected _name: string){ } public sayHi(): void { console.log("hi i am" + this._name); } } class AdminUser extends User { private _age: number; construtor (_name: string, _age: number){ super(_name); this._age = _age; } public sayHi(): void { console.log("my age: " + this._age); console.log("my name: " + this._name); super.sayHi(); } } var bob = new AdminUser("Bob", 23); bob.sayHi();
class User { name: string; constructor(name: string){ this.name = name; User.count++; } sayHi(): void { console.log("hi! i am" + this.name); } static count: number = 0; } var tom = new User("Tom"); var bob = new User("Bob"); console.log(User.count);
// interface interface Result{ a: number; b: number } function getTotal(result: Result){ return result.a + result.b; } var result = { a: 32, b: 55 }; console.log(getTotal(result)); // interface interface SpringResult { a: number; } interface FallResult { b: number; } interface FinalResult extends SpringResult, FallResult{ final: number; } function getTotal(result: FinalResult){ return result.a + result.b + result.final; } var result = { a: 32, b: 55, final: 67 }; console.log(getTotal(result));
interface GameUser{ socre: number; showScore(): void; } class User implements GameUser { name: string; score : number = 0; constructor(name: string){ this.name = name; } sayHi(): void { console.log("hi, i am" + this.name); } showSchore(): void { console.log("score" + this.score); } }
// generics function getArray<T>(value: T): T[]{ return [value, value, value]; } console.log(getArray<number>(3))
class MyData<T>{ constructor(public value: T){} getArray(): T[]{ return [this.value, this.value, this.value]; } } var v1 = new MyData<string>("hello"); console.log(v1.getArray()); var v2 = new MyData<number>(234); console.log(v2.getArray());
// 内部モジュール module UserModule { export var name = "sato"; export moudle AddressModule { export var zip = "111-1111"; } } console.log(UserModule.name); console.log(UserModule.AddressModule.zip);
// 外部モジュール import User = require("./user_commonjs") console.log(User.name);
[vagrant@localhost typescript]$ tsc main.ts -m commonjs