【问题标题】:Has type been deprecated in favor of interface?是否已弃用类型以支持接口?
【发布时间】:2020-01-16 02:05:13
【问题描述】:

我知道以下代码块是等效的。

export interface Person {
  id: number;
  name: string;
}
export type Person = {
  id: number;
  name: string;
}

我知道Typescript: Interfaces vs Types,但不知道何时使用type 而不是interface。猜猜type 的存在是有原因的。

https://www.typescriptlang.org/docs/home.html 上的手册没有提到type。我也无法在 https://duckduckgo.com/?q=site%3Atypescriptlang.org+type 上找到文档。是否有可能 type 已被弃用以支持 interface

谢谢!

【问题讨论】:

  • @AndrewMarshall 我知道这个问题,但它没有回答何时在接口上使用类型。
  • 列出了两者的区别。如果您需要某些功能,请选择提供它们的功能。如链接答案中所述,在某些情况下,一个人只能使用一种而不能使用另一种。例如,不能复制type Foo = numberinterface,也不能复制interfacetype 合并。
  • TypeScript 入门这么多方面有点抽象,但感谢分享@sagar.acharya。

标签: typescript


【解决方案1】:

它没有被弃用,因为 (1) 发行说明中没有提到它,并且 (2) type 确实存在于打字稿源代码中。另外,手册说,

因为软件的理想属性是对扩展开放,所以如果可能,您应该始终使用接口而不是类型别名。

另一方面,如果你不能用接口表达一些形状,而你需要使用联合或元组类型,类型别名通常是要走的路。

来源:https://www.typescriptlang.org/docs/handbook/advanced-types.html#interfaces-vs-type-aliases

基于此,您可能会推断,当interface 变得复杂时,最好使用type 而不是interface

【讨论】:

【解决方案2】:

类型别名没有被弃用,接口也没有被弃用,它们都有自己的用途。

对于简单的场景,两者之间几乎没有区别。您可以在大多数情况下互换使用它们。

类型别名支持多种高级类型,例如mapped typesconditional types

接口更好地支持某些递归场景,尽管类型别名在某些场景中也允许递归,并且接口中允许的递归性和类型别名之间的差距正在缩小(参见PR)。

接口还支持merging 与类和函数以及同一接口的其他重新声明。例如:

interface Box {
    height: number;
    width: number;
}

interface Box {
    scale: number;
}

let box: Box = {height: 5, width: 6, scale: 10};

另外值得一提的是,来自接口的对象类型不能分配给具有索引签名的类型,而来自类型别名的对象类型可以。

function fn(a: { [s:string]: string}){}

interface I { a: string}
type T = { a: string }

declare let i:I;
declare let t:T;

fn(i) //err
fn(t)

Play

【讨论】:

    【解决方案3】:

    我不完全确定两者的所有注意事项和最佳实践,但我所做的是以下

    我为组件中定义的所有类型添加接口。

    interface State {} // Interface the state defined in the component
    interface MappedState {} // Props provided to the component
    interface ComponentProps {} // Props provided to the components from from a through connect function
    

    最后,将它们添加到类型中

    type InjectedProps = ComponentProps  & MappedState & typeof mapDispatchToProps; // Redux's map dispatch to props function
    

    并将它们作为

    提供给组件
    class Component extends React.Component<InjectedProps, State> {
    

    我相信下面的guide 已经足够好了。是的,您必须进行研究并尝试理解它们。

    正如您在上述案例中看到的那样,使用类型来组合不同的接口是有意义的。

    您可以为传递给组件的不同类型的数据创建不同的接口。在做前端时最有用,而在后端接口的情况下必须足够。

    【讨论】:

    猜你喜欢
    • 2012-01-27
    • 1970-01-01
    • 2019-03-03
    • 2012-10-04
    • 2017-03-11
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多