TypeScript 中的接口与类型

编程入门 行业动态 更新时间:2024-10-21 23:22:38
本文介绍了TypeScript 中的接口与类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

TypeScript 中的这些语句(interface 与 type)有什么区别?

What is the difference between these statements (interface vs type) in TypeScript?

interface X { a: number b: string } type X = { a: number b: string };

推荐答案

2021 年 3 月更新:较新的 TypeScript 手册有一个部分 接口与类型别名,解释了这些差异.

Update March 2021: The newer TypeScript Handbook has a section Interfaces vs. Type Aliases which explains the differences.

原始答案 (2016)

根据 (现已存档)TypeScript 语言规范:

与总是引入命名对象类型的接口声明不同,类型别名声明可以为任何类型的类型引入名称,包括原始类型、联合类型和交集类型.

Unlike an interface declaration, which always introduces a named object type, a type alias declaration can introduce a name for any kind of type, including primitive, union, and intersection types.

规范继续提到:

接口类型与对象类型的类型别名有很多相似之处文字,但由于接口类型提供了更多的功能,它们是通常首选键入别名.例如接口类型

Interface types have many similarities to type aliases for object type literals, but since interface types offer more capabilities they are generally preferred to type aliases. For example, the interface type interface Point { x: number; y: number; }

可以写成类型别名

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

然而,这样做意味着失去以下功能:

However, doing so means the following capabilities are lost:

  • 可以在 extends 或 implements 子句中命名接口,但对象类型文字的类型别名不能自 TS 2.7 起不再适用.
  • 一个接口可以有多个合并声明,但有一个类型别名对于对象类型文字不能.
  • An interface can be named in an extends or implements clause, but a type alias for an object type literal cannot No longer true since TS 2.7.
  • An interface can have multiple merged declarations, but a type alias for an object type literal cannot.

更多推荐

TypeScript 中的接口与类型

本文发布于:2023-05-29 23:07:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/355068.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:接口   类型   TypeScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!