繁体   English   中英

TypeScript 接口是否推荐用于声明文件和 React 组件道具?

[英]Are TypeScript interfaces recommended for declaration files and React component props?

每当我需要为对象创建一个类型时,我通常会在我的declaration.d.ts中这样写它们:

type TagsObject = {
  _id: string;
  tag: string;
}

type ProjectData = {
  _createdAt: string;
  _id: string;
  _rev: string;
  _type: string;
  _updatedAt: string;
  tags: Array<TagsObject>;
}

对于 React 组件道具,我会这样写:

type IndexProps = {
  recentProjects: Array<ProjectData>;
  staticText: HomeStaticText;
};

export default function Index({ recentProjects, staticText }: IndexProps)

对于在declaration.d.ts中声明类型,我已经看到建议使用接口,因为它们更多地用于对象。 但是,对于 React 组件道具,我在网上研究时看到过使用类型和接口。

我知道接口和类型非常相似,但哪一个更适合用于声明和 React 组件道具?

声明文件的目的是在Javascript代码中引入Types ,而不是在Typescript代码中引入类型。 在 Typescript 中,您可以直接导入types.ts文件,也可以在与代码相同的目录中创建您的类型。

现在,来回答你的问题,

声明 object 类型的接口与类型。

接口是这样创建的

interface Person {
  name: string;
  age: string;
}

类型是这样创建的

type Person = {
  name: string;
  age: string;
}

接口和类型都有相似的用途,除了一些关键的区别

  1. 声明合并:可以在同一代码中多次定义接口。 接口的声明被Typescript合并在一起形成一个单一的接口。 这是它的样子
interface Person {
    name: string;
}

// it is completely okay to define the same interface again with new or existing 
// properties. But the same properties should have the same type.
interface Person {
    age: number;
}

// Now, the person interface contains two properties, name and age

另一方面,类型别名只能在代码中定义一次,不能再次重新声明。 尽管您可以在被视为局部变量的不同文件中声明相同的类型。 但是在同一个文件中,您不能再次定义类型。

  1. 开放接口以添加新属性

在声明合并的帮助下,接口允许我们向它们引入新属性,而类型别名则不能。

哪个更适合组件道具?

我会说两者。 我们不能选择一个。 但在我个人看来,我更喜欢使用 object 声明的接口,因为它们 go 与代码的其他部分很好。 由于 props 只定义一次,因此您也可以使用 type。 这是个人选择,而不是最佳实践。

访问Typescript 官方文档,亲自查看黑白类型和接口的差异。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM