TypeScript 入门教程 笔记与总结

489 阅读6分钟

原文:github.com/xcatliu/typ…

一、基础

1. 原始数据类型

// number string boolean
let decLiteral: number = 6;
let myName: string = 'Tom';
let isDone: boolean = false;

// undefined null
let u: void;
let u: undefined = undefined;
let n: null = null;

2. 任意值

let myFavoriteNumber: any = 'seven';
myFavoriteNumber = 7;

3. 联合属性

let myFavoriteNumber: string | number;
myFavoriteNumber = 'seven';
myFavoriteNumber = 7;

4. 对象

interface Person {
    name: string;
    age: number;
}

let tom: Person = {
    name: 'Tom',
    age: 25
};

4.1 可选属性

可选属性的含义是该属性可以不存在。

interface Person {
    name: string;
    age?: number;
}

let tom: Person = {
    name: 'Tom'
};

4.2 可选属性

使用 [propName: string] 定义了任意属性取 string 类型的值。 一旦定义了任意属性,那么确定属性和可选属性的类型都必须是它的类型的子集。

interface Person {
    name: string;
    age?: number;
    [propName: string]: any;
}

4.3 只读属性

希望对象中的一些字段只能在创建的时候被赋值,那么可以用 readonly 定义只读属性。

interface Person {
    readonly id: number;
    name: string;
    age?: number;
    [propName: string]: any;
}

5. 数组

let fibonacci: number[] = [1, 1, 2, 3, 5];

5.1 数组泛型

let fibonacci: Array<number> = [1, 1, 2, 3, 5];

5.2 用接口表示数组

只要索引的类型是数字时,那么值的类型必须是数字。

interface NumberArray {
    [index: number]: number;
}
let fibonacci: NumberArray = [1, 1, 2, 3, 5];

6. 函数

6.1 函数声明

let mySum: (x: number, y: number) => number = function (x: number, y: number): number {
    return x + y;
};

6.2 可选参数

function buildName(firstName: string, lastName?: string) {
    if (lastName) {
        return firstName + ' ' + lastName;
    } else {
        return firstName;
    }
}

6.3 参数默认值

function buildName(firstName: string, lastName: string = 'Cat') {
    return firstName + ' ' + lastName;
}
let tomcat = buildName('Tom', 'Cat');
let tom = buildName('Tom');

6.4 剩余参数

function push(array: any[], ...items: any[]) {
    items.forEach(function(item) {
        array.push(item);
    });
}

6.5 重载

重载允许一个函数接受不同数量或类型的参数时,作出不同的处理。

function reverse(x: number): number;
function reverse(x: string): string;
function reverse(x: number | string): number | string {
    if (typeof x === 'number') {
        return Number(x.toString().split('').reverse().join(''));
    } else if (typeof x === 'string') {
        return x.split('').reverse().join('');
    }
}

7. 类型断言

类型断言(Type Assertion)可以用来手动指定一个值的类型。

// 语法
<类型>值 
值 as 类型

function getLength(something: string | number): number {
    if ((<string>something).length) {
        return (<string>something).length;
    } else {
        return something.toString().length;
    }
}

7. 类型断言

当使用第三方库时,我们需要引用它的声明文件,才能获得对应的代码补全、接口提示等功能。

7.1 declare var 声明全局变量

declare let jQuery: (selector: string) => any;

7.2 declare function 声明全局方法

declare function jQuery(selector: string): any;

7.3 declare class 声明全局类

declare class Animal {
    name: string;
    constructor(name: string);
    sayHi(): string;
}

7.4 declare enum 声明全局枚举类型

declare enum Directions {
    Up,
    Down,
    Left,
    Right
}

7.5 declare namespace 声明(含有子属性的)全局对象

declare namespace jQuery {
    function ajax(url: string, settings?: any): void;
}

7.6 interface 和 type 声明全局类型

interface AjaxSettings {
    method?: 'GET' | 'POST'
    data?: any;
}
declare namespace jQuery {
    function ajax(url: string, settings?: AjaxSettings): void;
}

8. 内置对象

8.1 ECMAScript 的内置对象

Boolean、Error、Date、RegExp 等。

8.2 DOM 和 BOM 的内置对象

Document、HTMLElement、Event、NodeList 等。

二、进阶

1. 类型别名

type Name = string;
type NameResolver = () => string;
type NameOrResolver = Name | NameResolver;
function getName(n: NameOrResolver): Name {
    if (typeof n === 'string') {
        return n;
    } else {
        return n();
    }
}

2. 字符串字面量类型

type EventNames = 'click' | 'scroll' | 'mousemove';
function handleEvent(ele: Element, event: EventNames) {
    // do something
}

handleEvent(document.getElementById('hello'), 'scroll');  // 没问题
handleEvent(document.getElementById('world'), 'dbclick'); // 报错,event 不能为 'dbclick'

3. 元组

数组合并了相同类型的对象,而元组(Tuple)合并了不同类型的对象。

let tom: [string, number] = ['Tom', 25];

4. 枚举

枚举(Enum)类型用于取值被限定在一定范围内的场景。

enum Days {Sun, Mon, Tue, Wed, Thu, Fri, Sat};

5. 类

  • 类(Class):定义了一件事物的抽象特点,包含它的属性和方法
  • 对象(Object):类的实例,通过 new 生成
  • 面向对象(OOP)的三大特性:封装、继承、多态
  • 封装(Encapsulation):将对数据的操作细节隐藏起来,只暴露对外的接口。外- 界调用端不需要(也不可能)知道细节,就能通过对外提供的接口来访问该对象,同时也保证了外界无法任意更改对象内部的数据
  • 继承(Inheritance):子类继承父类,子类除了拥有父类的所有特性外,还有一些更具体的特性
  • 多态(Polymorphism):由继承而产生了相关的不同的类,对同一个方法可以有不同的响应。比如 Cat 和 Dog 都继承自 Animal,但是分别实现了自己的 eat 方法。此时针对某一个实例,我们无需了解它是 Cat 还是 Dog,就可以直接调用 eat 方法,程序会自动判断出来应该如何执行 eat
  • 存取器(getter & setter):用以改变属性的读取和赋值行为
  • 修饰符(Modifiers):修饰符是一些关键字,用于限定成员或类型的性质。比如 public 表示公有属性或方法
  • 抽象类(Abstract Class):抽象类是供其他类继承的基类,抽象类不允许被实例化。抽象类中的抽象方法必须在子类中被实现
  • 接口(Interfaces):不同类之间公有的属性或方法,可以抽象成一个接口。接口可以被类实现(implements)。一个类只能继承自另一个类,但是可以实现多个接口

5.1 访问修饰符

  • public 修饰的属性或方法是公有的,可以在任何地方被访问到,默认所有的属性和方法都是 public 的
class Animal {
    public name;
    public constructor(name) {
        this.name = name;
    }
}

let a = new Animal('Jack');
console.log(a.name); // Jack
a.name = 'Tom';
console.log(a.name); // Tom
  • private 修饰的属性或方法是私有的,不能在声明它的类的外部访问
class Animal {
    private name;
    public constructor(name) {
        this.name = name;
    }
}

let a = new Animal('Jack');
console.log(a.name); // Jack
a.name = 'Tom';

// index.ts(9,13): error TS2341: Property 'name' is private and only accessible within class 'Animal'.
// index.ts(10,1): error TS2341: Property 'name' is private and only accessible within class 'Animal'.
  • protected 修饰的属性或方法是受保护的,它和 private 类似,区别是它在子类中也是允许被访问的
class Animal {
    public name;
    protected constructor (name) {
        this.name = name;
  }
}
class Cat extends Animal {
    constructor (name) {
        super(name);
    }
}

let a = new Animal('Jack');

5.2 readonly

只读属性关键字,只允许出现在属性声明或索引签名中。

class Animal {
    readonly name;
    public constructor(name) {
        this.name = name;
    }
}

let a = new Animal('Jack');
console.log(a.name); // Jack
a.name = 'Tom';

// index.ts(10,3): TS2540: Cannot assign to 'name' because it is a read-only property.

5.3 抽象类

  • 首先,抽象类是不允许被实例化的
  • 其次,抽象类中的抽象方法必须被子类实现
abstract class Animal {
    public name;
    public constructor(name) {
        this.name = name;
    }
    public abstract sayHi();
}

class Cat extends Animal {
    public sayHi() {
        console.log(`Meow, My name is ${this.name}`);
    }
}

let cat = new Cat('Tom');

5.4 类实现接口

interface Alarm {
    alert();
}

class Door {
}

class SecurityDoor extends Door implements Alarm {
    alert() {
        console.log('SecurityDoor alert');
    }
}

class Car implements Alarm {
    alert() {
        console.log('Car alert');
    }
}

5.5 接口继承接口

interface Alarm {
    alert();
}

interface LightableAlarm extends Alarm {
    lightOn();
    lightOff();
}

5.6 接口继承类

class Point {
    x: number;
    y: number;
}

interface Point3d extends Point {
    z: number;
}

let point3d: Point3d = {x: 1, y: 2, z: 3};

5.7 混合类型

6. 泛型

泛型(Generics)是指在定义函数、接口或类的时候,不预先指定具体的类型,而在使用的时候再指定类型的一种特性。

function createArray<T>(length: number, value: T): Array<T> {
    let result: T[] = [];
    for (let i = 0; i < length; i++) {
        result[i] = value;
    }
    return result;
}

createArray<string>(3, 'x'); // ['x', 'x', 'x']

7. 声明合并

如果定义了两个相同名字的函数、接口或类,那么它们会合并成一个类型:

7.1 函数的合并

function reverse(x: number): number;
function reverse(x: string): string;
function reverse(x: number | string): number | string {
    if (typeof x === 'number') {
        return Number(x.toString().split('').reverse().join(''));
    } else if (typeof x === 'string') {
        return x.split('').reverse().join('');
    }
}

7.2 接口的合并

接口中的属性在合并时会简单的合并到一个接口中:

interface Alarm {
    price: number;
}
interface Alarm {
    weight: number;
}

相当于:

interface Alarm {
    price: number;
    weight: number;
}

7.3 类的合并

类的合并与接口的合并规则一致。