一、条件语句
二、函数
1、有名函数
function add(x:number, y:number):number {
return x + y;
}
2、匿名函数
let add = function (x:number, y:number):number {
return x + y;
}
- 函数可选参数
function buildName(firstname: string, lastname?:string) {
if (lastname) {
return firstname + lastname;
} else {
return firstname;
}
}
let result1 = buildName('wang');
let result2 = buildName('wang', 'xiaoming');
- 函数剩余参数
function buildName(a: string, ...restparams:string[]) {
return a + restparams.join('');
}
let result1 = buildName('wang');
let result2 = buildName('a', 'b', 'c');
3、箭头函数,匿名函数简写,省略了function关键字,可以将箭头函数赋值给变量;
(a, b, ...c)=> {}
let res = (a, b, ...c)=> {}
三、类
class Person {
private name:string // 定义私有属性
private age:number
constructor(name:string, age:number){ // 初始化构造函数
this.name = name;
this.age = age;
}
public getPersonInfo() { // 公共方法
return `my name is ${this.name} and is ${age}岁`;
}
}
let xiaoming = new Person('xiaoming', 18);
xiaoming.getPersonInfo()
四、继承
class Employee extends Person {
private department:string;
constructor(name:string, age:number, department:string) {
super(name,age); // 继承
this.department = department;
}
public getEmployeeInfo():string {
return this.getPersonInfo() + `and work in ${this.department}`
}
}
let person2 = new Employee('xiaoming', 18, 'tech');
person2.getPersonInfo()
person2.getEmployeeInfo()
五、模块