Blog
首页
文档
收藏
关于
  • 在线转换时间戳 (opens new window)
  • 在线压缩图片 (opens new window)
  • Float-Double转二进制 (opens new window)
  • 文件转Hex字符串 (opens new window)

HiuZing

🍑
首页
文档
收藏
关于
  • 在线转换时间戳 (opens new window)
  • 在线压缩图片 (opens new window)
  • Float-Double转二进制 (opens new window)
  • 文件转Hex字符串 (opens new window)
  • 前端面试题

  • JavaScript

  • Vue2

  • port

  • CSS

  • Node.js

  • JavaScript优化

  • uniapp

  • Mini Program

  • TypeScript

    • 基础

      • TypeScript介绍
      • TypeScript基础类型
      • TypeScript对象类型
      • TyprScript类型推论
      • TypeScript高级类型
      • TypeScript接口
      • TypeScript类型别名与接口的区别
        • TypeScript类型别名与接口的区别
          • 相同点
          • 不同点
      • TypeScript泛型
      • TypeScript项目配置
    • 实例

  • 面向对象编程

  • UI组件

  • Plugin

  • Vue3

  • 性能优化

  • Axios

  • 状态管理

  • React

  • Mock

  • Icon

  • Template

  • 构建工具

  • 项目规范配置

  • Taro

  • SVG

  • React Native

  • 前端
  • TypeScript
  • 基础
HiuZing
2022-09-27
目录

TypeScript类型别名与接口的区别

# TypeScript类型别名与接口的区别

在大多数的情况下使用接口类型和类型别名的效果等价,但是在某些特定的场景下这两者还是存在很大区别

TypeScript 的核心原则之一是对值所具有的结构进行类型检查。 而接口的作用就是为这些类型命名和为你的代码或第三方代码定义数据模型

type(类型别名)会给一个类型起个新名字。 起别名不会新建一个类型 - 它创建了一个新名字来引用那个类型。给基本类型起别名通常没什么用,尽管可以做为文档的一种形式使用

# 相同点

# 接口和类型别名都可以用来描述对象或函数的类型,只是语法不同

type MyTYpe = {
  name: string;
  say(): void;
}

interface MyInterface {
  name: string;
  say(): void;
}
1
2
3
4
5
6
7
8
9

# 允许扩展

  • interface 用 extends 来实现扩展

    interface MyInterface {
      name: string;
      say(): void;
    }
    
    interface MyInterface2 extends MyInterface {
      sex: string;
    }
    
    let person:MyInterface2 = {
      name:'宝贝',
      sex:'女',
      say(): void {
        console.log("hello 啊,树哥!");
      }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
  • type 使用 & 实现扩展

    type MyType = {
      name:string;
      say(): void;
    }
    type MyType2 = MyType & {
      sex:string;
    }
    let value: MyType2 = {
      name:'宝贝',
      sex:'女',
      say(): void {
        console.log("hello");
      }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14

# 不同点

type可以声明基本数据类型别名/联合类型/元组等,而interface不行

类型别名:不仅可以为对象指定类型,实际上可以为任意类型指定别名

// 基本类型别名
type UserName = string;
type UserName = string | number;
// 联合类型
type Animal = Pig | Dog | Cat;
type List = [string, boolean, number];
1
2
3
4
5
6

interface能够合并声明,而type不行

interface Person {
  name: string
}
interface Person {
  age: number
}
// 此时Person同时具有name和age属性
1
2
3
4
5
6
7

具体来源 (opens new window)

#TS
上次更新: 2024/08/14, 04:14:33
TypeScript接口
TypeScript泛型

← TypeScript接口 TypeScript泛型→

最近更新
01
React Native 使用SVG
08-13
02
Docker基础命令
08-04
03
算数逻辑单元
07-30
更多文章>
Theme by Vdoing | Copyright © 2021-2024 WeiXiaojing | 友情链接
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式