首页 > 解决方案 > 声明文件和 React 组件道具是否推荐使用 TypeScript 接口?

问题描述

每当我需要为对象创建类型时,我通常会在我的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 组件道具?

标签: reactjstypescript

解决方案


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

现在,来回答你的问题,

接口与类型来声明对象类型。

接口是这样创建的

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. 开放接口以添加新属性

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

哪个更适合组件道具?

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

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


推荐阅读