个人博客 个人博客
首页
  • 前端
  • 后端
  • Git
  • Docker
  • 网络
  • 操作系统
工具
阅读
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

董先亮

前端react开发
首页
  • 前端
  • 后端
  • Git
  • Docker
  • 网络
  • 操作系统
工具
阅读
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • HTML

  • CSS

  • JavaScript

  • TypeScript

    • interface 与 type
      • interface 与 type 区别
      • 如何选择
    • 类型
    • 工具类
    • tsconfig详解
  • 前端基础
  • TypeScript
NeverStop1024
2022-06-18
目录

interface 与 type

# interface 与 type 区别

interface叫接口,type叫类型别名,虽然都能用来定义类型,严谨来说 type是一种赋值引用,interface是真正意义伤的类型定义

  1. type 可以是联合类型、元组类型、基本类型,interface只能是对象
type Name = string // 基本类型,用的少
type A = {x: string} // 类型赋值引用
type B = {y: number}
type TypeA = A | B // 联合类型
type TypeB = [A , B] // 元组类型
type DotPosition = 'top' | 'bottom' | 'left' | 'right'; // 联合类型
1
2
3
4
5
6
  1. 相同type别名不能被多次定义,interface可以被定义多次,并会合并到一起
type A = {name: string}
// type A = {age: number} // 重复定义 Error

interface B {
    name: string
}
interface B {
    age: number
}
// 相当于
interface B {
    name: string
    age: number
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
  1. type 能用in,interface不能用
type Keys = 'first' | 'second'
type B = {
    [key in Keys]: string
}

const demo: B = {
    first: 'a',
    second:'b'
}


// interface 做法
interface A {
    [key: Keys]: string
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  1. 默认导出方式不同
    • interface支持声明同时默认导出,type必须先声明,再单独导出
export default interface Config {
    name: string
}

type Config2 = {name: string}
export default Config2
1
2
3
4
5
6
  1. 扩展方式不同
  • interface用extends,type用 & 操作符
interface A {
    name: string
}
interface B extends A {
    age: number
}

// type
type A = {name: string}
type B = {age: number} & A
1
2
3
4
5
6
7
8
9
10

# 如何选择

  1. 搭配使用
type DotPosition = 'top' | 'bottom' | 'left' | 'right'; // 联合类型
interface A {
    name: string;
    direction: DotPosition
}
1
2
3
4
5
  1. 单纯定义类型,使用interface,需要操作用type
export type NativeButtonProps = {
    htmlType?: ButtonHTMLType;
    onClick?: React.MouseEventHandler<HTMLElement>;
} & BaseButtonProps &
    Omit<React.ButtonHTMLAttributes<any>, 'type' | 'onClick'>;

export type AvatarSize = 'large' | 'small' | 'default' | number | ScreenSizeMap;

export type LocaleComponentName = Exclude<keyof Locale, 'locale'>;

1
2
3
4
5
6
7
8
9
10
编辑 (opens new window)
上次更新: 2022/06/19
Map与Set
类型

← Map与Set 类型→

最近更新
01
mock使用
07-12
02
websocket即时通讯
07-12
03
前端面试题
07-09
更多文章>
Theme by Vdoing | Copyright © 2022-2023 NeverStop1024 | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式