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

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

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

3182 次点击
所在节点    程序员
31 条回复
xieqiqiang00
2022-07-18 22:43:37 +08:00
从来都是用 type ,没用过 Interface
darkengine
2022-07-18 22:50:53 +08:00
我都是 interface 一把梭
Dragonphy
2022-07-18 22:55:02 +08:00
typescript 对我来说就是多了个 interface🤣
zhuweiyou
2022-07-18 23:09:04 +08:00
我定义结构用 interface ,类型别名用 type
wunonglin
2022-07-18 23:11:51 +08:00
Interface 顾名思义,用来定义接口,当然用来定义 Object 也可以。
Type 用来定义一个变量的类型。


如果定义 Object 的话,但是还是建议用 Class 代替 Interface ,因为在运行时也有作用,instanceof 可以在运行时判断类型,从而达到不同的 Class 可以做不同的事,就不必老是用 obj.type === xxx 了
Kaciras
2022-07-18 23:23:40 +08:00
优先 Interface ,只在别名和运算时采用 Type
Leviathann
2022-07-18 23:24:00 +08:00
type
官方说用 interface 是因为官方一直尽量避免宣传类型语言这个存在但是写出来比较别扭的东西
比如要用 extends 模拟三目里的 equals 的部分
beginor
2022-07-18 23:24:55 +08:00
简单类型用 type

```ts
export type Visibility = 'visible' | 'none';
```

复杂类型用 interface

```ts
export interface Model {
id?: number;
name?: string;
}
```
dcsuibian
2022-07-18 23:34:15 +08:00
For the most part, you can choose based on personal preference, and TypeScript will tell you if it needs something to be the other kind of declaration. If you would like a heuristic, use interface until you need to use features from type.

来自官方手册:
https://www.typescriptlang.org/docs/handbook/2/everyday-types.html
Jasonwxy
2022-07-18 23:53:05 +08:00
https://pro.ant.design/zh-CN/docs/type-script#%E4%BB%80%E4%B9%88%E6%97%B6%E5%80%99%E6%8E%A8%E8%8D%90%E7%94%A8-type-%E4%BB%80%E4%B9%88%E6%97%B6%E5%80%99%E7%94%A8-interface-
Jasonwxy
2022-07-18 23:57:55 +08:00
@dcsuibian #9 很好奇为啥官方推荐 interface🤔
Chingim
2022-07-19 00:16:01 +08:00
“如果是声明 Type 的话, 其他地方随便用, 不需要 import 定义接口的文件”

这句话是什么意思?为什么用 type 就不需要 import 就可以直接用了?
DOLLOR
2022-07-19 00:56:46 +08:00
type 声明同名的 type 会报错,提示重复标识符。
interface 声明同名 interface 会发生合并,这往往是非预期行为,会造成迷惑。
所以我选择 非必要,不 interface 。
dcsuibian
2022-07-19 01:11:38 +08:00
@Jasonwxy
我个人认为:interface 比 type 更能体现出面相对象的思想,而 type 则更能体现出 ts 结构化类型的特点。
nonone
2022-07-19 01:24:05 +08:00
type 灵活啊 可以各种范形
Trim21
2022-07-19 01:57:22 +08:00
很好奇为什么你声明的 type 不用导入…
AyaseEri
2022-07-19 08:42:50 +08:00
interface 与 type 混用会导致 IDE 推断的时候只展示类型名称,不展示类型的定义内容。
但是又得做体操,所以我选择 type
DICK23
2022-07-19 09:24:22 +08:00
type 也需要导入啊。
interface 支持重载,type 就不行
Yeen
2022-07-19 09:57:52 +08:00
如果熟悉老旧的 com 规范的话,可以对 interface 本身有更深入的理解
mudssky
2022-07-19 11:11:50 +08:00
我一般用的都是 interface ,都是 js 对象类型的。
其他类型我会用 type
主要是我更喜欢 extends 语法,不太喜欢用那个交叉类型

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

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

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

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

© 2021 V2EX