第5章 接口与类型别名 
基本用法 
声明
- readonly代表该项只读
- ?代表该项可选
ts
interface IPerson {
  readonly id: number;
  name: string;
  age: number;
  sex?: string;
}
type Person = {
  readonly id: number;
  name: string;
  age: number;
  sex?: string;
};继承
- interface使用- extends关键字继承
- type使用- &合并类型
ts
interface IAnimal {
  run(): void;
}
interface IPerson extends IAnimal {
  id: number;
  name: string;
  age: number;
  sex: string;
}
type Animal = {
  run(): void;
};
type Person = Animal & {
  id: number;
  name: string;
  age: number;
  sex: string;
};索引签名
- 索引签名的思想是在只知道键和值类型的情况下对结构未知的对象进行类型划分
- TypeScript 还有一个实用类型 Record<Keys, Type>,类似于索引签名。
ts
interface User {
  [key: string]: string;
}
type UserType = {
  [key: string]: string;
};
// 效果同上
type UserType2 = Record<string, string>;约束函数 
基本用法
- 有大括号时,interface和type都使用冒号声明返回值类型
- 没有大括号时,type 不使用大括号时,使用 => 声明返回值类型
ts
interface IAdd {
  (a: number, b: number): number;
}
type Add = {
  (a: number, b: number): number;
};
type Add = (a: number, b: number) => number声明 this 类型
- 定义类型时,必须定义为 this,且位于第一个
- 传入的形参从定义时的第二个参数开始
ts
type FnWithThis = (this: Person, name: string) => void;
const sayHi: FnWithThis = function (name: string) {
  console.log(name);
};
const rose: Person = {
  name: 'Rose',
  sayHi
};
rose.sayHi('Jack');约束对象 
class 实现接口
ts
class Person implements IPerson {
  id: number;
  name: string;
  age: number;
  sex: string;
  constructor(id: number, name: string, age: number, sex: string) {
    this.id = id;
    this.name = name;
    this.age = age;
    this.sex = sex;
  }
  run() {
    console.log('人跑路');
  }
}字面量使用接口
ts
const zhichao: IPerson = {
  id: 1,
  name: 'lbviic',
  age: 18,
  sex: '男',
  run() {
    console.log('我跑路');
  }
};type 与 interface 的区别 
- type使用等号进行声明,而- interface不需要
- type可以描述基本数据类型,- interface不可以描述基本数据类型,只可以描述对象
- type只是类型别名,- interface则是类型声明
- type不可以重复赋值,- interface重复声明会自动合并ts- interface IPerson { name: string; } interface IPerson { age: number; } // 以下代码不正确,type 不可以重名 type Person = { name: string; } type Person = { age: number; }









