TypeScript
1. const & let
let lang: string = 'TypeScript';
let age: number = 89;
let age_2 =64;
const pi :number = 3.1415926;
2. 解构
let input = [89,64,65,2018,10];
let [first,second] = input;
console.log(first);
console.log(second);
let [one,...other] = input;
console.log(...other);
let newArray = [89,...other,18];
console.log(newArray);
let o = {
a: "foo",
b: 12,
c: "bar"
};
let {a,b} = o;
console.log(a,b);
3. 函数
function add(x: number,y: number):number{
return x+y;
}
let myAdd = function(x: number, y: number): number{return x+y;};
console.log(myAdd(1,2));
function greeting(firstName: string, lastName?: string){
if(lastName)
return `Hello ${firstName} ${lastName}`;
return `Hello ${firstName}`;
}
console.log(greeting("Zhou"));
console.log(greeting("Zhou","Wang"));
function greeting_2(firstName: string, lastName = 'Wang'){
return `Hello ${firstName} ${lastName}`;
}
console.log(greeting_2("Zhou"));
console.log(greeting_2("Zhou","Zeng"));
function greeting_3(firstName: string, ...restName: string[])
{
return `Hello ${firstName} ${restName.join(' ')}`;
}
let greeting1 = () => `Hello TS!`;
console.log(greeting1());
let greeting2 = (name: string) => `Hello ${name}`;
console.log(greeting2("Zhou"));
let add2 = (a: number, b: number) => a+b;
let add3 = (a: number, b : number) =>{
let s=a+b;
return s;
}
console.log(add3(1,2));
4. 类
class MyInfo {
name: string;
weather: string;
constructor(name: string, weather: string){
this.name = name;
this.weather = weather;
}
printInfo(): void {
console.log(`Hello, ${this.name}.`);
console.log(`Today is ${this.weather}.`);
}
}
let myData = new MyInfo('QiGe', 'raining');
myData.printInfo();
5. 类的属性和函数的访问权限
class MyInfo2 {
public name: string;
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 = new MyInfo2('QiGe', 'raining');
myData2.printInfo();
6. 静态属性
console.log(Math.round(89.64));
console.log(Math.pow(2, 8));
class MyStaticClass {
static place = 'Earth';
static printInfo() {
console.log('We have only one Earth!');
}
}
console.log(MyStaticClass.place);
MyStaticClass.printInfo();
7. 继承
class Animal {
constructor(public name: string) { }
protected log(message: string) {
console.log(message);
}
move(distanceInMeters: number = 0) {
this.log(`${this.name} moved ${distanceInMeters}m.`);
this.log('==============');
}
}
class Horse extends Animal {
constructor(name: string) {
super(name);
}
run(distanceInMeters = 50) {
this.log("Clop, clop...");
super.move(distanceInMeters);
}
}
class Eagle extends Animal {
constructor(name: string) { super(name); }
reborn() {
console.log('Reborn? It is a joke, hahaha!');
}
}
let tom: Horse = new Horse("Tommy the Palomino");
tom.run(8964);
let sam: Eagle = new Eagle("Sammy the Hawk");
sam.move(1024);
sam.reborn();
|