为什么在指定条件下在Typescript中首选interface或type(如果有的话)? [英] Why would interface or type be preferred (if anything) in Typescript under specified condition?

查看:146
本文介绍了为什么在指定条件下在Typescript中首选interface或type(如果有的话)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题不是这一个的重复,尽管标题相似.我不是在问差异,而是要问差异的含义.另外,我已经考虑过基于意见的风险,并通过限制为两个可行的选项并指定一组条件来使之无效.

This question is not a dupe of this one, despite the similarites in the title. I'm not asking about the differences but the implications of the differences. Also, I've considered the risk of being opinion-based and voided it by limiting to two viable options and specifying a set of conditions.

我问了基于类型的答案,该方法行之有效.

I asked a question and got a type based answer, which worked.

export type Configs = {
  [key: string]: ButtonConfig | TextBoxConfig | CheckConfig;
}

当我将其应用到项目中时,IDE TSLint提出了使用基于接口的方法的建议.

When I applied that in my project, the IDE TSLint'ed a sugestion to apply interface based approach instead.

export interface Configs {
  [key: string]: TextBoxConfig | ButtonConfig | CheckConfig;
}

这是两种根本不同的方法,根据最佳实践,我很好奇哪种方法最合适以及何时使用.一组类似的博客提供了允许为类型创建新名称",而"提供了定义实体的强大方法".就像说"这个大"和"那个有香蕉"一样.

Those are two fundamentally different approaches and I got curious as to which would be most appropriate and when, according to best practices. A set of blogs like this one offer comparison tables. However, I'm confused as to the implication of said differences. For instance: "allows the creation of the new name for a type" is hard to evaluare versus "provides the powerful way to define entities", from my point of view. It's like saying "this one is large" and "that one has bananas".

我发现了也与其他博客和文档相抵触并纠正. SO也有一些问题,但是我发现的是,列出偏差,而不是详细说明.总而言之,我不清楚如何解释信息库.

I've found blogs that contradict and correct other blogs and docs, too. There are questions on SO too but those I've found, list the deviations rather than elaborating on the implications thereof. All in all, it's unclear to me how to interpret the info base.

原始海报@thorjacobsen回答说,由于

The original poster, @thorjacobsen, replied that in his team they went for type based because of semantical preference, which is a local reason, not guaranteed to be applicable in a general case.

从我收集到的所有信息中,我感觉到(除非其他要求做出选择),界面被.NET(对键的熟悉程度)来自团队,而 type 则更受其欢迎. >是具有JS经验(历史感)的团队的首选.注意,我在这里推测.

Of what I gathered, I get a sense that (unless other requirements impose a choice), interface is preferred by teams coming from .NET (keywork familiarity) while type is preferred by team with JS experience (historial sentiment). NB, I'm speculating here.

鉴于时间在变化并且方法论适应了时空,我不知道在一般情况下会建议使用两者中的哪一个(如果有的话)作为最佳实践(或者是在获得更多信息之前最安全的选择). /p>

Given that times change and the methodics adapts to the wind of time, I wonder which one (if any) of the two would be suggested in a general case as the best practice (or safest bet until more info emerges).

推荐答案

首先,事实是:此答案和<一个href ="https://stackoverflow.com/a/52682220/1903366">这个带有示例的是绝对正确的.

First, the facts: this answer and this one with examples are absolutely correct.

接口提供的关于类型的唯一内容是声明合并.另一方面,类型比接口(映射类型,条件类型等)能做的更多.

The only thing interfaces offer over types is declaration merging. On the other side, types can do a lot more than interfaces (mapped types, conditional types, etc).

现在,您可以理解为什么会这样设计语言:

Now, you understandably wonder why the language was designed that way:

令我困惑的是,我收集到的两种信息实际上是等效的,可以实现相同的目标.看起来(几乎)是一个问题,并且计算机语言不是以这种方式创建的.如果可能,我们选择最佳方法并将其设置为默认方法.换句话说,引入特征x是没有意义的,已经有特征y在做同样的事情.

What confuses me in the information I've gathered is that there are two, virtually equivalent approaches to achieve the same kind of goal. It seems that it's (almost) a matter of taste and computer languages are not created that way. We pick the most optimal approach and make it default, if possible. In other words, there's no point introducing feature x and there's already feature y that's doing the same thing.

通过提供有关TypeScript历史的背景,我将尽力回答这个问题.

I'll try to answer this as well as I can by giving some background on the history of TypeScript.

从一开始,TypeScript就具有接口来定义对象或函数的命名类型:

From the very beginning TypeScript has had interfaces as a way to define the named type of an object or function:

interface Foo {
    bar: number;
}

但是,在某些情况下,不必一定要为TypeScript指定接口来了解对象的结构.举个例子:

However, in some situations you didn't necessarily have to specify an interface for TypeScript to understand the structure of an object. Take this example:

let foo = {
    bar: 42
}

编译器将推断 foo具有类型{ bar: number }.甚至可以在不创建界面的情况下手动注释类型:

The compiler will infer that foo has the type { bar: number }. It's even possible to manually annotate the type without creating an interface:

let foo: { bar: number } = {
    bar: 42
}

这表明总是可以在没有接口的情况下创建复杂类型.只是没有办法给它们起个名字,以使其更具可读性和可重复使用性.

This shows that it was always possible to create complex types without interfaces. There was just no way to put a name to them as to make them more readable and re-usable.

然后 TypeScript 1.4引入了类型别名.新的type关键字允许为任何类型的类型定义备用名称.它们适用于接口:

Then TypeScript 1.4 introduced type aliases. The new type keyword allows to define an alternative name for any kind of type. They work for interfaces:

MyFoo = Foo

但是对于以前无法使用名称定义的类型:

But also for types which previously couldn't be defined using a name:

type MyNumberArray = number[];
type MyFunction = (arg: string) => void;

当然,这意味着我们现在也只能使用type定义接口Foo:

Of course this now meant we can also define our interface Foo only using type:

type Foo = {
    bar: number;
};

因为 TypeScript 1.6 ,类型别名也可以是通用的,允许它们描述TypeScript已知的所有可能的类型构造.

Since TypeScript 1.6, type aliases could be generic as well allowing them to describe all possible type constructs known to TypeScript.

总结:类型被设计为类型别名,这是为任何类型命名的一种方式.这包括接口可以代表的任何类型.

To summarize: Types are designed to be type aliases, a way of giving any type a name. This includes any type that an interface can represent.


使用哪个是个人喜好问题.没有对与错,除了保持一致很重要.以下是一些可供选择的选项(我忽略此处的声明合并,因为在大多数项目中未使用该声明)

Which one to use is a matter of personal taste. There is no right or wrong, except that it's important to be consistent. The following are a few options how one could decide to go about this (I'm ignoring declaration merging here because in most projects it's not used)

  • 始终使用类型
    一种适用于一切的语法
  • 除非需要类型,否则始终使用界面
    对于更熟悉接口的语法和语义的开发人员
  • 类的接口,其他所有类型的
    对于更熟悉类和接口语义的开发人员
  • Always use types
    One syntax for everything
  • Always use interfaces unless types are needed
    For devs who are more comfortable with the syntax and semantics of interfaces
  • Interfaces for classes, types for everything else
    For devs who are more comfortable with the semantics of classes and interfaces

当然,还有更多的方法可以完成,并且您必须找到适合自己需求的东西.

Of course there are many more ways to do it, and you'll have to find something that suits your needs.

这篇关于为什么在指定条件下在Typescript中首选interface或type(如果有的话)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆