TS中的Type和Interface

发布时间 2023-08-01 15:06:51作者: sanhuamao

学习内容来源于:https://www.youtube.com/watch?v=Idf0zh9f3qQ

Type 与 Interface的区别

  1. 编写方式
  2. 继承方式

**Type 的优势 **

  1. Interface只能描述对象,而Type还可以描述其他类型如stringnumberboolean
  2. Type可以描述联合类型和Interface不行
  3. Type在使用Utility Types时更简洁
  4. Type在使用Tuples时更简洁
  5. Type可以从其他地方直接抽取类型
  6. Interface会自动合并,而Type不会

Type 与 Interface的区别

  1. 编写方式
type UserProps = {
	name: string;
	age: number;
}

interface UserProps {
	name: string;
	age: number;
}
  1. 继承方式
// type 写法
type UserProps = {
	name: string;
	age: number;
}
type AdminProps = UserProps & {
	role: string
}

// interface 写法
interface UserProps {
	name: string;
	age: number;
}
interface AdminProps extends UserProps {
	role: string
}

Type 相较于 Interface的优势

  1. Interface只能描述对象,而Type还可以描述其他类型如stringnumberboolean
type Address = string
  1. Type可以描述联合类型和Interface不行
type Address = string | string[]
  1. Type在使用Utility Types时更简洁
type UserProps = {
	name: string;
	age: number;
	createAt : Date
}
// 在UserProps的基础上去掉createAt
type GuestProps = Omit<UserProps, "createAt">
// 如果删除多个
type GuestProps = Omit<UserProps, "name" | "age">


// 如果使用interface,将会是:
interface GuestProps extends Omit<UserProps, "name" | "age">

Utility Types文档

  1. Type在使用Tuples时更简洁
type Address = [string, number]

// 如果使用interface,将会是:
interface Address extends Array<number | string>{
	0: number;
	1: string
}
  1. Type可以从其他地方直接抽取类型
const project = {
	title: "Project 1",
	specification: {
		areaSize: 100,
		rooms: 3
	}
}

// 抽取全部类型
type Specification = typeof project
// --- 等价于:
type Specification = {
	title: string;
	specification: {
		areaSize: number;
		rooms: number;
	}
}

// 抽取里边的specification类型
type Specification = typeof project["specification"]
// --- 等价于:
type Specification = {
	areaSize: number;
	rooms: number;
}
  1. Interface会自动合并,而Type不会
interface User{
	name: string;
	age: number;
}

interface User{
	role: string;
}

let user:User

// Type不允许声明两个同名的type