数据类型
数字、字符串、布尔
let decLiteral: number = 6;
let name: string = "bob";
let isDone: boolean = false;
数组
let list: number[] = [1, 2, 3];
let list2: Array<number> = [1, 2, 3];
元组:当访问一个已知索引的元素,会得到正确的类型;当访问一个越界的元素,会使用联合类型替代。
let x: [string, number];
x = ['hello', 10];
x[3] = 'world'; //ok
x[6] = true; // error
枚举:默认情况下,从0开始为元素编号,也可以手动的指定成员的数值。而且也可以由枚举的值得到它的名字。
enum Color {a, b, c}
let color: Color = Color.b; //1
enum Color2 {a, b = 5, c}
let color2: Color2 = Color2.c; //6
let colorName: string = Color2[5]; //b
Any:任意类型
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false;
let list: any[] = [1, true, "free"];
list[2] = 100;
Void:没有任何类型,只能赋予undefined和null
function warnUser(): void {
console.log("This is my warning message");
}
let unusable: void = undefined;
Null 和 Undefined:默认情况下null和undefined是所有类型的子类型。当指定了–strictNullChecks标记,null和undefined只能赋值给void和它们各自。在某处想传入一个 string或null或undefined,可以使用联合类型string | null | undefined。
let u: undefined = undefined;
let n: null = null;
let decLiteral: number = undefined;
Never:never类型表示的是永不存在的值的类型。
function error(message: string): never {
throw new Error(message);
}
function fail() {
return error("Something failed");
}
function infiniteLoop(): never {
while (true) {
}
}
Object
let prettySure: Object = {};
类型断言
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
let strLength2: number = (someValue as string).length;
函数
函数类型:参数类型和返回值类型。
function add(x: number, y: number): number {
return x + y;
}
推断类型:在赋值语句的一边指定了类型但是另一边没有类型的话,TypeScript编译器会自动识别出类型
function add(x: number, y: number) {
return x + y;
}
可选参数:在参数名旁使用 ?
function buildName(firstName: string, lastName?: string) {
if (lastName)
return firstName + " " + lastName;
else
return firstName;
}
剩余参数:不知道会有多少参数传递进来时使用
function buildName(firstName: string, ...restOfName: string[]) {
return firstName + " " + restOfName.join(" ");
}
let employeeName = buildName("Joseph", "Samuel", "Lucas", "MacKinzie");
类
修饰符
- public:默认值
class Animal {
public name: string;
public constructor(theName: string) { this.name = theName; }
public move(distanceInMeters: number) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
- private:私有的,外部及子类中都不能访问,自然也都不可以修改
class Animal {
private name: string;
constructor(theName: string) { this.name = theName; }
}
new Animal("Cat").name; // 错误: 'name' 是私有的.
- protected:受保护的,子类中可以访问,外部不可以
class Animal {
protected name: string;
constructor(theName: string) { this.name = theName; }
}
class Cat extends Animal{
constructor(name: string) {
super(name);
}
hello(){
console.log(this.name); // 'name'
this.name = 'name2';
console.log(this.name); // 'name2'
}
}
new Cat('name').hello();
new Cat('name').name; // 错误: 'name' 是受保护的.
- readonly:只读,必须在声明时或构造函数里被初始化
class Octopus {
readonly name: string;
constructor (theName: string) {
this.name = theName;
}
}
let dad = new Octopus("Man with the 8 strong legs");
dad.name = "Man with the 3-piece suit"; // 错误! name 是只读的.
存取器:通过getters/setters来截取对对象成员的访问
let passcode = "secret passcode";
class Employee {
private _fullName: string;
get fullName(): string {
console.log(123)
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 = "secret passcode";
console(employee.fullName);
static:静态属性,存在于类本身上面而不是类的实例上
class Animal {
static abc: string = 'abc';
constructor() {
console.log(Animal.abc)
}
}
new Animal();
new Animal().abc; // error
abstract:抽象类,做为其它派生类的基类使用,抽象类中的抽象方法不包含具体实现并且必须在派生类中实现。
abstract class Department {
constructor(public name: string) {}
printName(): void {
console.log('Department name: ' + this.name);
}
abstract printMeeting(): void; // 必须在派生类中实现
}
class AccountingDepartment extends Department {
constructor() {
super('Accounting and Auditing'); // 在派生类的构造函数中必须调用 super()
}
printMeeting(): void {
console.log('The Accounting Department meets each Monday at 10am.');
}
generateReports(): void {
console.log('Generating accounting reports...');
}
}
let department: Department; // 允许创建一个对抽象类型的引用
department = new Department(); // 错误: 不能创建一个抽象类的实例
department = new AccountingDepartment(); // 允许对一个抽象子类进行实例化和赋值
department.printName();
department.printMeeting();
department.generateReports(); // 错误: 方法在声明的抽象类中不存在
接口
interface LabelledValue {
label: string;
}
let labelledValue: LabelledValue = {
label: 'abc'
}
let labelledValue2: LabelledValue = {
value: 'abc'
} // error
let labelledValue2: LabelledValue = {
label: 'abc'
value: 'abc'
} // error
可选属性、只读属性、任意属性
interface SquareConfig {
color?: string;
readonly x: number;
[propName: string]: any;
}
函数类型
interface SearchFunc {
(source: string, subString: string): boolean;
}
let mySearch: SearchFunc = function(source, subString) {
let result = source.search(subString);
return result > -1;
}
可索引的类型
interface StringArray {
[index: number]: string;
}
let myArray: StringArray = ["Bob", "Fred"];
类类型
interface ClockInterface {
currentTime: Date;
setTime(d: Date);
}
class Clock implements ClockInterface {
currentTime: Date;
setTime(d: Date) {
this.currentTime = d;
}
constructor(h: number, m: number) { }
}
继承接口
interface Shape {
color: string;
}
interface PenStroke {
penWidth: number;
}
interface Square extends Shape, PenStroke {
sideLength: number;
}
let square = <Square>{};
square.color = "blue";
square.sideLength = 10;
square.penWidth = 5.0;
混合类型
interface Counter {
(start: number): string;
interval: number;
reset(): void;
}
function getCounter(): Counter {
let counter = <Counter>function (start: number) { };
counter.interval = 123;
counter.reset = function () { };
return counter;
}
let c = getCounter();
c(10);
c.reset();
c.interval = 5.0;
接口继承类
class Control {
private state: any;
}
interface SelectableControl extends Control {
select(): void;
}
class Button extends Control implements SelectableControl {
select() { }
}
class TextBox extends Control {
select() { }
}
// 错误:“Image”类型缺少“state”属性。
class Image implements SelectableControl {
select() { }
}
泛型
泛型类型
function identity<T>(arg: T): T {
return arg;
}
let myIdentity: <T>(arg: T) => T = identity;
let myIdentity1: <U>(arg: U) => U = identity;
let myIdentity2: {<T>(arg: T): T} = identity;
interface GenericIdentityFn3 {
<T>(arg: T): T;
}
let myIdentity3: GenericIdentityFn3 = identity;
interface GenericIdentityFn4<T> {
(arg: T): T;
}
let myIdentity4: GenericIdentityFn4<number> = identity;
泛型类
class GenericNumber<T, U> {
zeroValue: T;
add: (x: U) => U;
constructor(a: T, b: U){
this.zeroValue = a;
this.add = b => b;
}
}
let myGenericNumber = new GenericNumber(1, 'asd');
泛型约束
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
return arg.length;
}