学习笔记:interface和type的区别

739 阅读2分钟

前言


最近看了几篇关于 interface 和 type异同的博客。了解了他们之间的区别。本文将会通过大量的示例代码详细介绍这两者的异同。希望对小伙伴的学习有所帮助。

interface vs type

先让我们看看官方规范对于二者的解释

  • An interface can be named in an extends or implements clause, but a type alias for an object type literal cannot.
  • An interface can have multiple merged declarations, but a type alias for an object type literal cannot.

相同点

1. 两者都可以用来描述对象或函数的类型,但是语法不同。

  • interface
interface IPoint {
    readonly x:number
    readonly y:number
}
interface ISetPoint {
    (params:IPoint):IPoint
}
interface IPoint {
    readonly x: number
    readonly y: number
}
interface ISetPoint {
    (params: IPoint): IPoint
}

let p: IPoint = {
    x: 3,
    y: 4
}
const setPoint:ISetPoint = (point)=>{
    return point
}
  • type
type IPoint = {
    readonly x: number
    readonly y: number
}
type ISetPoint = {
    (params: IPoint): IPoint
}

let p: IPoint = {
    x: 3,
    y: 4
}
const setPoint:ISetPoint = (point)=>{
    return point
}

type 声明需要加等号,但是interface不需要。

2. 两者都可以实现继承

  • interface 实现继承(extends)
interface IPoint1 {
    readonly x: number
    readonly y: number
}

interface IPoint2 extends IPoint1 {
    readonly z: number
}

let p: IPoint2 = {
    x: 1,
    y: 1,
    z: 1
}
  • type实现继承(&)
type IPoint1 = {
    readonly x: number
    readonly y: number
}

type IPoint2 = IPoint1 & {
    readonly z: number
}

let p: IPoint2 = {
    x: 1,
    y: 1,
    z: 1
}
  • 二者可以相互继承
type IPoint1 = {
    readonly x: number
    readonly y: number
}

interface IPoint2 extends IPoint1  {
    readonly z: number
}

let p: IPoint2 = {
    x: 1,
    y: 1,
    z: 1
}
interface IPoint1 {
    readonly x: number
    readonly y: number
}

type IPoint2 = IPoint1 & {
    readonly z: number
}

let p: IPoint2 = {
    x: 1,
    y: 1,
    z: 1
}

interface 和 type 都是可以实现继承的,并且可以相互继承。但是小伙伴们一定要记住 interface 使用 extends 实现继承;type 使用 & 实现继承

3.类可以以相同的方式实现接口或类型别名

interface IPoint {
  x: number;
  y: number;
}

class Point1 implements IPoint {
  x: 1;
  y: 2;
}

type TPoint = {
  x: number;
  y: number;
};

class Point2 implements TPoint {
  x: 1;
  y: 2;
}

不同点

1. type 可以声明基本类型别名,联合类型,元组等类型

// 基本类型别名
type Name = string;

// 联合类型
type PartialPointX = { x: number; };
type PartialPointY = { y: number; };
type PartialPoint = PartialPointX | PartialPointY;

// 具体定义数组每个位置的类型
type Data = [number, string];

// 只能从定义中选择一个
type Addr = "海淀区" | "朝阳区"
let a:Addr = "海淀区"

2. type可以生成映射类型

type 能使用 in 关键字生成映射类型,但 interface 不行。

type Name = "firstName" | "lastName"

type DudeType = {
    [key in Name]: string
}

const test: DudeType = {
    firstName: "xiaoye",
    lastName: "huo"
}

3. 与类型别名不同,接口可以定义多次,并将被视为单个接口(合并所有声明的成员)。

interface Point { x: number; }
interface Point { y: number; }

const point: Point = { x: 1, y: 2 };

总结

一般来说,如果不清楚什么时候用interface/type,能用 interface 实现,就用 interface , 如果不能就用 type 。

如有错误,欢迎指正。

您的一个点赞,就是对我最大的鼓励。