[ts入门03]interface和type

294 阅读1分钟

interface和type是什么?

interface是接口类型

  • 可以被extend继承("Extends and implements" )
  • 可以属性合并("Declaration merging")

type是类型别名

  • 可以给基本类型设置别名

type 和 interface 都可以

当二者描述一个Object时,就很相似

// interface
interface IPerson {
    firstName: string
    lastName: string
}
interface Iadd  {
    (x:number, y:number):number
}
  
// type
type Person = {
    firstName: string
    lastName: string
}
type Add = {
    (x:number, y:number):number
};

type 可以而 interface 不行

基本类型别名,联合类型,元组等类型

// 基本类型别名
type id = number

// 联合类型
type Names = "zhangsan" | "lisi";

// 具体定义数组每个位置的类型
type List = ["abc", number]

使用 typeof 获取实例类型进行赋值

// typeof进行赋值
const initialState = {
  todos: [] as Todo[],
};
type TodoState = typeof initialState;

interface 可以而 type 不行

声明合并

// 声明合并 IPerson包含 firstName, lastName, nickName属性
interface IPerson {
  firstName: string
  lastName: string
}

interface IPerson {
  nickName: string
}

怎么用比较好?

use whatever suites you and your team, just be consistent

interface和type可以使用,但是注意的是整个团队应该保持统一