let lang:string='TypeScript';//如果省略类型说明,TS也会进行自动推断// lang = 1010;//error!如果需要使用联合类型:let lang: number | string = 'TS';let age:number=89;let age_2 =64;const pi :number=3.1415926;//pi的值不能被改变,类似常量// pi = 3.14;//error
//访问权限classMyInfo2{//class是关键字,类名默认全部大写首字母public name:string;//public属性,可省略private _weather:string;//私有属性,习惯以_开头进行命名constructor(name:string, weather:string){//构造函数,一般用于初始化this.name = name;this._weather = weather;}printInfo():void{//其它函数this._test();console.log(`Hello, ${this.name}.`);console.log(`Today is ${this._weather}.`);}private_test():void{console.log('You can not call me outside!');}}let myData2 =newMyInfo2('QiGe','raining');//使用new关键字生成对象// console.log(myData._weather); //error!// myData2._test(); //error
myData2.printInfo();
6. 静态属性
//静态属性,内建或自定义,无需new即可使用console.log(Math.round(89.64));//90console.log(Math.pow(2,8));//256classMyStaticClass{static place ='Earth';staticprintInfo(){console.log('We have only one Earth!');}}console.log(MyStaticClass.place);
MyStaticClass.printInfo();
7. 继承
classAnimal{// 当构造函数传入的参数加上了“访问权限控制符”,则同时会声明同名类属性,并赋值constructor(public name:string){}protectedlog(message:string){console.log(message);}move(distanceInMeters:number=0){this.log(`${this.name} moved ${distanceInMeters}m.`);//请注意name来自何处this.log('==============');}}classHorseextendsAnimal{constructor(name:string){super(name);// 通过super调用父类构造器}run(distanceInMeters =50){//自己独有的函数this.log("Clop, clop...");super.move(distanceInMeters);// 通过super调用父类方法}}classEagleextendsAnimal{constructor(name:string){super(name);}reborn(){//自己独有的函数console.log('Reborn? It is a joke, hahaha!');}}let tom: Horse =newHorse("Tommy the Palomino");
tom.run(8964);let sam: Eagle =newEagle("Sammy the Hawk");
sam.move(1024);//sam的move函数来自何处?
sam.reborn();
TypeScript1. const & letlet lang: string = 'TypeScript';//如果省略类型说明,TS也会进行自动推断// lang = 1010;//error!如果需要使用联合类型:let lang: number | string = 'TS';let age: number = 89;let age_2 =64;const pi :number = 3.1415926;//pi的值不能被改变,类似常量// pi = 3.14;//error