详解Vue3.0 前的 TypeScript 最佳入门实践

2020-06-14 06:02:51易采站长站整理
可以而
interface
不行

type
可以声明基本类型别名,联合类型,元组等类型


// 基本类型别名
type Name = string

// 联合类型
interface Dog {
wong();
}
interface Cat {
miao();
}

type Pet = Dog | Cat

// 具体定义数组每个位置的类型
type PetList = [Dog, Pet]

type
语句中还可以使用
typeof
获取实例的 类型进行赋值


// 当你想获取一个变量的类型时,使用 typeof
let div = document.createElement('div');
type B = typeof div

其他骚操作


type StringOrNumber = string | number;
type Text = string | { text: string };
type NameLookup = Dictionary<string, Person>;
type Callback<T> = (data: T) => void;
type Pair<T> = [T, T];
type Coordinates = Pair<number>;
type Tree<T> = T | { left: Tree<T>, right: Tree<T> };

interface
可以而
type
不行

interface
能够声明合并


interface User {
name: string
age: number
}

interface User {
sex: string
}

/*
User 接口为 {
name: string
age: number
sex: string
}
*/

interface
有可选属性和只读属性

可选属性

接口里的属性不全都是必需的。 有些是只在某些条件下存在,或者根本不存在。 例如给函数传入的参数对象中只有部分属性赋值了。带有可选属性的接口与普通的接口定义差不多,只是在可选属性名字定义的后面加一个

?
符号。如下所示


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

只读属性

顾名思义就是这个属性是不可写的,对象属性只能在对象刚刚创建的时候修改其值。 你可以在属性名前用

readonly
来指定只读属性,如下所示:


interface User {
readonly loginName: string;
password: string;
}

上面的例子说明,当完成User对象的初始化后loginName就不可以修改了。

3.4 实现与继承:

implements
vs
extends