typescript进阶体验

一、类型别名

概述:类型别名用来给一个类型起个新名字
案例:

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

二、字符串字面量类型

概述:用来约束取值只能是某几个字符串中的一个
案例:

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

handleEvent(document.getElementById('hello'), 'scroll');  // ok
handleEvent(document.getElementById('world'), 'dbclick'); // error:  event 不能为 'dbclick'

三、元组

概述:数组合并了相同类型的对象,而元组(Tuple)合并了不同类型的对象 (更高级的数组)

1.定义一对值分别为 string 和 number 的元组: 

let xcatliu: [string, number] = ['Xcat Liu', 25];

2.直接对元组类型的变量进行初始化或者赋值的时候,需要提供所有元组类型中指定的项

let xcatliu: [string, number];
xcatliu = ['Xcat Liu', 25];  // ok
let xcatliu: [string, number] = ['Xcat Liu'];  // error

3.当添加越界的元素时,它的类型会被限制为元组中每个类型的联合类型

let xcatliu: [string, number]; 
xcatliu = ['Xcat Liu', 25];  // ok
xcatliu.push('http://xcatliu.com/');  // ok
xcatliu.push(true);  // error: Argument of type 'boolean' is not assignable to parameter of type 'string | number'

四、枚举

概述:枚举(Enum)类型用于取值被限定在一定范围内的场景,比如一周只能有七天,颜色限定为红绿蓝等。

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

1.给枚举项手动赋值:

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

console.log(Days["Sun"] === 7);  // true
console.log(Days["Mon"] === 1);  // true
console.log(Days["Tue"] === 2);  // true
console.log(Days["Sat"] === 6);  // true

// 当然,手动赋值的枚举项也可以为小数或负数,此时后续未手动赋值的项的递增步长仍为 1

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

console.log(Days["Sun"] === 7);  // true
console.log(Days["Mon"] === 1.5);  // true
console.log(Days["Tue"] === 2.5);  // true
console.log(Days["Sat"] === 6.5);  // true

2.常数项和计算所得项

概述:枚举项有两种类型:常数项和计算所得项

(1)一个典型的计算所得项的例子(如果紧接在计算所得项后面的是未手动赋值的项,那么它就会因为无法获得初始值而报错)

enum Color {Red, Green, Blue = "blue".length};  // ok
enum Color {Red = "red".length, Green, Blue};  // error

3.常数枚举

概述:常数枚举是使用 const enum 定义的枚举类型

(1)常数枚举与普通枚举的区别是,它会在编译阶段被删除,并且不能包含计算成员

const enum Directions { Up, Down, Left, Right }
let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right];

//编译成js后
var directions = [0 /* Up */, 1 /* Down */, 2 /* Left */, 3 /* Right */];

(2)假如包含了计算成员,则会在编译阶段报错

const enum Color {Red, Green, Blue = "blue".length}; // error: In 'const' enum declarations member initializer must be constant expression


4.外部枚举

概述:外部枚举是使用 declare enum 定义的枚举类型

(1)declare 定义的类型只会用于编译时的检查,编译结果中会被删除

declare enum Directions { Up, Down, Left, Right }
let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right];

//编译成js后
var directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right];

(2)外部枚举和常数枚举同时使用

declare const enum Directions { Up, Down, Left, Right }
let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right];

//编译成js后
var directions = [0 /* Up */, 1 /* Down */, 2 /* Left */, 3 /* Right */];

五、类

概述:TypeScript 除了实现了所有 ES6 中的类的功能以外,还添加了一些新的用法

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

1.TypeScript 中类的修饰符:public、private 和 protected

  • public 修饰的属性或方法是公有的,可以在任何地方被访问到,默认所有的属性和方法都是 public 的
  • private 修饰的属性或方法是私有的,不能在声明它的类的外部访问
  • protected 修饰的属性或方法是受保护的,它和 private 类似,区别是它在子类中也是允许被访问的

(1)很多时候,我们希望有的属性是无法直接存取的,这时候就可以用 private 了

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

let a = new Animal('Jack');
console.log(a.name);  // error:  Property 'name' is private and only accessible within class 'Animal'
a.name = 'Tom';  // error:  Property 'name' is private and only accessible within class 'Animal'

(2)private属性子类不能继承:

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

class Cat extends Animal {
    constructor(name) {
        super(name);
        console.log(this.name); // error: Property 'name' is private and only accessible within class 'Animal'
    }
}


2.抽象类

概述:abstract 用于定义抽象类和其中的抽象方法

注意:抽象类是不允许被实例化的,抽象类中的抽象方法必须被子类实现:

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

class Cat extends Animal {
    public eat() {
        console.log(`${this.name} is eating.`);
    }
}

let animal = new Animal();  // error:  Cannot create an instance of an abstract class.
let cat = new Cat('Tom');  //error:  class 'Cat' does not implement inherited abstract member 'sayHi' from class 'Animal'


3.类的类型(给类加上 TypeScript 的类型很简单,与接口类似)

class Animal {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
    sayHi(): string {
      return `My name is ${this.name}`;
    }
}

let a: Animal = new Animal('Jack');
console.log(a.sayHi()); // My name is Jack


六、类与接口

1.类实现接口

实现(implements)是面向对象中的一个重要概念。一般来讲,一个类只能继承自另一个类,有时候不同类之间可以有一些共有的特性,这时候就可以把特性提取成接口(interfaces),用 implements 关键字来实现。

(1)案例1:

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');
    }
}

(2)案例2:一个类可以是实现多个接口

interface Alarm {
    alert();
}

interface Light {
    lightOn();
    lightOff();
}

class Car implements Alarm, Light {
    alert() {
        console.log('Car alert');
    }
    lightOn() {
        console.log('Car light on');
    }
    lightOff() {
        console.log('Car light off');
    }
}

2.接口继承接口(接口与接口之间可以是继承关系)

interface Alarm {
    alert();
}

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

3.接口继承类

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

interface Point3d extends Point {
    z: number;
}

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


4.混合类型

(1)可以使用接口的方式来定义一个函数需要符合的形状

interface SearchFunc {
    (source: string, subString: string): boolean;
}

let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
    return source.search(subString) !== -1;
}

(2)接口定义函数内部的属性和方法

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;


七、泛型

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

1.案例:

(1)首先,我们来实现一个函数 createArray,它可以创建一个指定长度的数组,同时将每一项都填充一个默认值:

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

createArray(3, 'x');  // ['x', 'x', 'x']

(2)使数组中每一项都应该是输入的 value 的类型

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']

注:在函数名后添加了 <T>,其中 T 用来指代任意输入的类型,在后面的输入 value: T 和输出 Array<T> 中即可使用了;然后在调用的时候,可以指定它具体的类型为 string。当然,也可以不手动指定,而让类型推论自动推算出来

2.多个类型参数

概述:定义泛型的时候,可以一次定义多个类型参数

function swap<T, U>(tuple: [T, U]): [U, T] {
    return [tuple[1], tuple[0]];
}

swap([7, 'seven']);  // ['seven', 7]

3.泛型约束

(1)案例1:在函数内部使用泛型变量的时候,由于事先不知道它是哪种类型,所以不能随意的操作它的属性或方法

function loggingIdentity<T>(arg: T): T {
    console.log(arg.length);  // error:  property 'length' does not exist on type 'T'
    return arg;
}


(2)案例2:可以对泛型进行约束,只允许这个函数传入那些包含 length 属性的变量。这就是泛型约束

interface Lengthwise {
    length: number;
}

function loggingIdentity<T extends Lengthwise>(arg: T): T {
    console.log(arg.length);
    return arg;
}

注:使用 extends 约束了泛型 T 必须符合接口 Lengthwise 的形状,也就是必须包含 length 属性;此时如果调用 loggingIdentity 的时候,传入的 arg 不包含 length,那么在编译阶段就会报错了

(3)案例三:多个类型参数之间也可以互相约束

function copyFields<T extends U, U>(target: T, source: U): T {
    for (let id in source) {
        target[id] = (<T>source)[id];
    }
    return target;
}

let x = { a: 1, b: 2, c: 3, d: 4 };

copyFields(x, { b: 10, d: 20 });

注:上例中,我们使用了两个类型参数,其中要求 T 继承 U,这样就保证了 U 上不会出现 T 中不存在的字段。

4.泛型接口

(1)使用含有泛型的接口来定义函数的形状

interface CreateArrayFunc {
    <T>(length: number, value: T): Array<T>;
}

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

createArray(3, 'x'); // ['x', 'x', 'x']

(2)把泛型参数提前到接口名上,此时在使用泛型接口的时候,需要定义泛型的类型

interface CreateArrayFunc<T> {
    (length: number, value: T): Array<T>;
}

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

createArray(3, 'x'); // ['x', 'x', 'x']


5.泛型类(与泛型接口类似,泛型也可以用于类的类型定义中)

class GenericNumber<T> {
    zeroValue: T;
    add: (x: T, y: T) => T;
}

let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x + y; };

6.泛型参数的默认类型

概述:当使用泛型时没有在代码中直接指定类型参数,从实际值参数中也无法推测出时,这个默认类型就会起作用。

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


八、声明合并

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

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('');
    }
}


2.接口的合并

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

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

//相当于:

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


注意:合并的属性的类型必须是唯一的

(2)接口中函数的合并,等同于函数的重载

interface Alarm {
    price: number;
    alert(s: string): string;
}
interface Alarm {
    weight: number;
    alert(s: string, n: number): string;
}

// 相当于:
interface Alarm {
    price: number;
    weight: number;
    alert(s: string): string;
    alert(s: string, n: number): string;
}

3.类的合并 (其使用方式与接口的合并保持一致)

猜你喜欢

转载自blog.csdn.net/WU5229485/article/details/82820929