type 和 interface的异同

简介: type 和 interface的异同
// 使用type定义一个类型
type Person = {
  name: string;
  age: number;
}
// 使用interface定义一个类型
interface Animal {
  name: string;
  age: number;
}
// 使用type定义一个函数签名
type Add = (a: number, b: number) => number;
// 使用interface定义一个函数签名
interface Subtract {
  (a: number, b: number): number;
}
// 使用type定义一个泛型
type Container<T> = {
  value: T;
}
// 使用interface定义一个泛型
interface Box<T> {
  value: T;
}
// 使用type进行类型别名
type Score = number;
type Name = string;
// interface是一个合并类型,可以多次声明同一个接口
interface User {
  name: string;
}
interface User {
  age: number;
}
// type不是合并类型,如果重复定义会报错
type Person = {
  name: string;
}
type Person = {
  age: number;
} // 报错!重复定义
// type可以使用联合类型和交叉类型
type A = string | number;
type B = { name: string } & { age: number };

type 和 interface 在绝大多数情况下可以互换使用,都能够定义对象类型、函数类型、泛型类型等。不过有一些微小的差别:

  1. interface在声明合并时,会将同名属性进行合并,而type会报错。
  2. type可以使用联合类型和交叉类型,而interface不能直接使用。
  3. type可以为基本类型(如number、string等)定义类型别名,interface不可以。
  4. 当定义类型别名时,使用type更为直观;当定义对象类型时,使用interface更为直观。

一般来说,如果你不确定该使用type还是interface,可以优先选择interface,因为它在使用上更加直观,并且可以方便地声明合并。

相关文章
|
8月前
|
Cloud Native Java Go
关于 interface{} 会有啥注意事项?上
关于 interface{} 会有啥注意事项?上
|
13天前
|
JavaScript 安全 前端开发
TypeScript 基础学习笔记:interface 与 type 的异同
TypeScript 基础学习笔记:interface 与 type 的异同
13 0
|
2月前
|
JavaScript
TS中 type和interface的区别
TS中 type和interface的区别
18 0
|
2月前
|
JavaScript
type和interface的异同?
type和interface的异同?
13 0
|
2月前
|
设计模式 存储 安全
什么是编程语言里的 Tag Interface
什么是编程语言里的 Tag Interface
|
2月前
|
JavaScript
Typescript中 interface 和 type 的区别是什么?
在 TypeScript 中,interface 和 type 都用于定义类型,但它们有一些区别。
50 0
|
2月前
|
JavaScript 前端开发 索引
TS - interface和type的区别
TS - interface和type的区别
25 0
|
8月前
|
Cloud Native Go
关于 interface{} 会有啥注意事项?下
关于 interface{} 会有啥注意事项?下
|
11月前
|
编解码
Type C接口浅析01
Type C接口浅析01
182 1
|
10月前
|
Swift
Swift中AnyObject、Any、AnyClass、T.self、T.Type、type(of:)、Self的使用和区别
Swift中AnyObject、Any、AnyClass、T.self、T.Type、type(of:)、Self的使用和区别
126 0