typescript可以通过 typeinterface 对变量复杂类型定义,虽然大部分情况下两者的功能类似,但是还是有些许差别。

type的常见用法

type Age = number;

const myAge: Age = 20;

type People = {
  age: number;
  height: number;
}

const kelen: People = {
  age: 20,
  height: 180
}

// 限制变量的值范围,只允许其中的一种
type Sex = "girl" | "boy" | "none";

const mySex = "boy";

interface的常见用法

interface People {
  age: number;
  height: number;
}

const kelen: People = {
  age: 20,
  height: 180
}

可以看到 typeinterface 在语法上稍微有点差异,但是都可以做到类型保护的功能,比如上面的 people 这个类型,除了最普通的变量类型定义,还有扩展类型用法,typeinterface 可以互相继承

type和interface混用

type和interface既然有相同点,在使用上也是可以混合使用

type扩展类型

type Animal = {
  name: string
}

type Bear = Animal & {
  honey: boolean
}

interface扩展类型

interface Animal {
  name: string
}

interface Bear extends Animal {
  honey: boolean
}

interface扩展type

type Animal = {
  name: string,
}

interface Bear extends Animal {
  honey: boolean;
}

type扩展interface

interface Animal {
  name: string,
}

type Bear = Animal & {
  honey: boolean
}

type和interface的区别

虽然从上面的例子上看两者区别不大,但是ts出现这两种特性肯定有差异,废话少说,下面总结下差异

type独有的功能

组合

interface People {
  name: string,
  weight: number
}
type Animal = {
  name: string,
}
type Cat = People | Animal

type Fruit = 'apple' | 'pear' | 'orange';
type Vegetable = 'broccoli' | 'carrot' | 'lettuce';
// 'apple' | 'pear' | 'orange' | 'broccoli' | 'carrot' | 'lettuce';
type HealthyFoods = Fruit | Vegetable;

元组

元组用来定义数组的某一位置的元素类型,只能通过 type 来定义

type ResponseCode = [string, number];

类型捕捉

当我们想要拷贝某一个对象的类型,可以通过 type 来实现

const orange = { color: "Orange", vitamin: 1}
// { color: string, vitamin: number }
type Fruit = typeof orange
let apple: Fruit;
apple = { color: "Red", vitamin: 2 }

可以看到,type 会自动捕捉到 color 是 string 类型,vitamin 是 number 类型

遍历属性

type 可以通过 in 来生成映射类型

type Keys = "firstName" | "lastName";

type Name = {
  [key in Keys]: string;
};

const myName: Name = {
  firstName: "kelen",
  lastName: "huang",
};

interface独有的功能

定义合并

interface 定义会自动合并,type 则无法重复定义

interface Animal {
  name: string
}

interface Animal {
  age: number
}

ts会自动合并成一个,如下

interface Animal {
  name: string,
  age: number,
}
// 使用
const Bear: Animal = {
  name: 'bear',
  age: 20
}

 

本文为原创,未经授权,禁止任何媒体或个人自媒体转载
商业侵权必究,如需授权请联系[email protected]
标签: typescript ts