Typescript 基础类型:
1 | // Any |
Typescript 函数
1 | // function foo(x: 参数): 函数返回类型 {} |
书写完整函数类型
这种函数类型看着有点怪,1
2let myAdd: (baseValue: number, increment: number) => number =
function(x: number, y: number): number { return x + y; };
默认参数
1 | function name (firstName: string, lastName: string ="someName"){ |
可选参数
在参数后面加上 “?” 被确定为可选参数.1
2
3function buildName(firstName: string, lastName?: string) {
}
剩余参数
1 | function buildNa么(firstN: string, ...restOfName: string[]){ |
Typescript interface 接口
(参考)[https://zhongsp.gitbooks.io/typescript-handbook/content/doc/handbook/Interfaces.html];
interface 和 abstract 区别
interface 是接口,所有的方法都是抽象方法,成员变量是默认的public static final 类型。接口不能实例化自己.
abstract class 是抽象类,至少包含一个抽象方法的累叫抽象类,抽象类不能被自身实例化,并用abstract关键字来修饰.
interface
1 | interface SquareConfig { |
Typescript 类
一个简单的类
1 | class Greeter { |
getter & setter
typescript 允许自定义getter 和 setter1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20let passcode = "secret passcode";
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (passcode && passcode == "secret passcode") {
this._fullName = newName;
}
else {
console.log("Error: Unauthorized update of employee!");
}
}
}
let employee = new Employee();
employee.fullName = "Bob Smith";
继承
1 | class Animal { |
修饰符: public, protected, private 和 readonly
public
所有人都可以访问.
protected
只有类里面或者子类可以访问.
private
只有在类里面可以进行访问.
readonly
只能读取不能再赋值
静态属性
用 static 关键字来声明1
2
3
4
5
6
7
8
9
10
11class Grid {
//声明
static origin = {x: 0, y: 0};
calculateDistanceFromOrigin(point: {x: number; y: number;}) {
//调用
let xDist = (point.x - Grid.origin.x);
let yDist = (point.y - Grid.origin.y);
return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale;
}
constructor (public scale: number) { }
}
抽象类
1 | 抽象类 |