跳到主要内容

interface和type

什么时候使用 interface 和 type?

  • 在使用 TypeScript 开发项目时,interface 和 type 都是用来定义自定义类型的工具。

  • 一般来说,使用 interface 来定义对象的形状,以及接口的继承和实现。

  • 它们是一种合约,用于描述对象应该具有的属性和方法。

例如:
interface Person {
name: string
age: number
sayHello(): void
}

class Employee implements Person {
name: string
age: number
position: string

constructor(name: string, age: number, position: string) {
this.name = name
this.age = age
this.position = position
}

sayHello() {
console.log(`Hello, my name is ${this.name}.`)
}
}

const john: Person = new Employee('John', 28, 'Manager')
john.sayHello()
  • 相较之下,type 语句更为灵活,可以用于定义各种类型。
  • 它可以给任何已知的类型创建一个别名,包括基本类型、联合类型、交叉类型、元组等。
例如:
type Point = {
x: number
y: number
}

type Rectangle = Point & {
width: number
height: number
}

const rect: Rectangle = {
x: 0,
y: 0,
width: 100,
height: 200,
}
  • type 还可以使用类型操作符进行更复杂的类型转换和运算符。此外,type 还可以用于定义函数类型和映射类型等高级概念。

  • interface 适用于对象和类的描述,提供了更多的额外功能(如接口继承和实现),

  • 而 type 适用于类型别名,能够处理更复杂的类型操作。


使用 interface 更合适时

  • 当要描述一个“形状固定”的对象或类时,使用 interface 通常更合适。
  • interface 可以定义对象的属性、方法和类的实现,可以使用 extends 关键字进行接口继承。它提供了更强的类型检查和编译器支持。
例如,当我们要描述一个人的信息时,可以使用 interface:
interface Person {
name: string
age: number
sayHello(): void
}

const john: Person = {
name: 'John',
age: 28,
sayHello() {
console.log(`Hello, my name is ${this.name}.`)
},
}

使用 type 更合适时

  • 而当需要创建自定义类型别名,进行联合类型、交叉类型、映射类型等操作时,type 会更灵活。
  • type 可以给任何已知的类型创建一个别名,并且可以使用类型操作符进行更复杂的类型定义。
例如,当需要创建一个联合类型表示数字或字符串时,可以使用 type:
type NumberOrString = number | string

function printValue(value: NumberOrString) {
console.log(value)
}

printValue(5) // 输出:5
printValue('Hello') // 输出:Hello
  • interface 和 type 并不是完全互换的,它们有一些细微的差异和应用场景。

语法写法不同

  • 当你需要定义一个函数类型时,可以使用interface或者type。它们的区别在于语法和一些细微的特性。
使用interface来定义函数类型的语法如下:
interface MyFunction {
(arg1: number, arg2: string): boolean
}
而使用type来定义函数类型的语法如下:
type MyFunction = (arg1: number, arg2: string) => boolean

虽然语法不同,但在大多数情况下,这两种方式是等价的,你可以根据个人喜好来选择使用哪种方式。

  • 然而,type有一些高级的特性,在函数类型的定义中可能更有用。
  • 例如,你可以使用type来定义重载函数类型,以支持多种不同参数和返回值类型的组合。
  • 示例如下:
type MyFunction = {
(arg1: number): string
(arg1: string): number
}

在上述示例中,MyFunction被定义为一种重载函数类型,它可以接受一个number类型参数并返回string类型,或者接受一个string类型参数并返回number类型。