typescript 中声明一个类型, 是用 Interface 还是 Type 呢?

2022-07-18 22:31:25 +08:00
 bthulu

Interface 的话, 其他地方用到的时候, 还得 import 定义接口的文件. 如果是声明 Type 的话, 其他地方随便用, 不需要 import 定义接口的文件. 看起来是 Type 方便多了, 但为什么官方说要尽量用 Interface?

3204 次点击
所在节点    程序员
31 条回复
Qcui
2022-07-19 13:14:21 +08:00
比较倾向 interface ,做扩展、继承更符合直观一些
dssxzuxc
2022-07-19 13:34:57 +08:00
都能用的情况下用 interface ,不得不用 type 的时候再用 type
daliusu
2022-07-19 13:51:33 +08:00
interface 声明结构
type 声明类型

除非你有特殊需求,比如声明一些基本类型、或者做多个类型自动合并
GiantHard
2022-07-19 14:08:24 +08:00
Interface 在编译性能上的优势: https://github.com/microsoft/TypeScript/wiki/Performance#preferring-interfaces-over-intersections

> However, and as soon as you need to compose two or more types, you have the option of extending those types with an interface, or intersecting them in a type alias, and that's when the differences start to matter.

Interface 在编译错误友好性上的优势: https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#differences-between-type-aliases-and-interfaces

> Prior to TypeScript version 4.2, type alias names may appear in error messages, sometimes in place of the equivalent anonymous type (which may or may not be desirable). Interfaces will always be named in error messages.
qianxi0410
2022-07-19 15:41:16 +08:00
我都用 type ,然后 eslint 自动帮我改成 interface 。。。
codehz
2022-07-19 15:48:11 +08:00
interface 可以多次合并,这种放在诸如 dom api 这种可能有多个不同声明文件的就非常合适(
但是 type 可以用 union 类型和 intersection 类型等高级类型,这个 interface 做不了(而且也不能“继承”这样的高级类型)
realJamespond
2022-07-19 17:33:16 +08:00
type 不好搞 generic, interface 比较好搞, 不搞泛型可以用 type
Vaspike
2022-07-20 09:46:24 +08:00
我的理解是 type 做别名比较合适,比如 map 里泛型是 string 和 map 就可以 type 声明后直接用
interface 更多的是对象思想,如果你要把很多属性平级拼装那就用 interface
yukinotech
2022-08-06 16:51:28 +08:00
1. interface 里面可以用 this
2. interface 可以 extends 另一个类型,比如 interface Props extends ViewProps {name:string}
3. interface 可以多次声明,重载

p.s 本人是能用 type 尽量用 type, 可能是需要和 class 打交道的场景基本为 0
noyidoit
2022-11-15 23:23:17 +08:00
@dcsuibian 我在 handbook 看到了这句话,没看明白这个 heuristic 于是搜索到了这里 XD ,您知道这里的 heuristic 是什么意思吗?我查了词典解释是"proceeding to a solution by trial and error or by rules that are only loosely defined",中文就仨字:启发式,不太明白这跟 interface 有什么联系
dcsuibian
2022-11-16 02:39:58 +08:00
@noyidoit 我也翻译不出来。
但按我的理解这句话意思就是说:如果你是个选择困难症,那就用 interface ,interface 不满足要求了再用 type 。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/867120

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX