Skip to content
Spotify - 每月低于 10 元

第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>;

约束函数

基本用法

  • 有大括号时,interfacetype 都使用冒号声明返回值类型
  • 没有大括号时,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 的区别

  1. type 使用等号进行声明,而 interface 不需要

  2. type 可以描述基本数据类型,interface 不可以描述基本数据类型,只可以描述对象

  3. type 只是类型别名,interface 则是类型声明

  4. type 不可以重复赋值,interface 重复声明会自动合并

    ts
    interface IPerson {
      name: string;
    }
    interface IPerson {
      age: number;
    }
    
    // 以下代码不正确,type 不可以重名
    type Person = {
      name: string;
    }
    type Person = {
      age: number;
    }
关注微信公众号搬瓦工 - 美国 CN2 优化线路
你认为这篇文章怎么样?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0

预览:

评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v3.1.3