reactjs - typescript 语法

标签 reactjs typescript react-redux typescript-generics

我是 TypeScript 的新手,并且正在使用我公司的一个大量使用它的存储库。 (我们正在构建一个 React/Redux 应用程序。)我熟悉 TypeScript 泛型的基本概念,但有一个特定的语法令人困惑。这是相关代码的示例(位于 reducer 中):

interface EntityState<Entity> {
  entity?: Entity;
  status: ApiStatus; // enum
}

interface FieldSummary {
    dataType?: string;
    // other properties...
}

function singleField(state: EntityState<FieldSummary> = defaultEntityState, 
  action: ActionTypes) {...}

有人能解释一下EntityState<FieldSummary>吗?是在做?如果需要更多详细信息,请告诉我。

最佳答案

这是泛型类型参数的示例。

interface EntityState<Entity> {
  entity?: Entity;
  status: ApiStatus;
}

该接口(interface)将包含一个可选的实体?,其类型稍后定义。目前,它被称为Entity

当您使用此接口(interface)时,您提供类型,因此:

const stringEntity: EntityState<string>;

属性stringEntity.entity将是字符串未定义(假设它是可选的)。

const numEntity: EntityState<number>;

属性numEntity.entity将是一个数字未定义

等等。使用接口(interface)时提供的类型参数可以是满足任何约束的任何类型 - 在您的情况下,类型参数是不受约束的。这意味着您可以重用接口(interface),因为类型是稍后定义的。

关于reactjs - typescript 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53321903/

相关文章:

angularjs - share() vs ReplaySubject : Which one, 都不起作用

javascript - 使用 API 调用更新 React-Redux 中的组件状态

javascript - 重新渲染整个播放列表的文本框上的 onBlur 函数阻止了切换到下一个文本框的能力

reactjs - 检查渲染方法

reactjs - ElectronJS打印HTML文档的高度问题

jquery - 从基类方法获取派生类名称

android - react 导航 3 : Back button in Android doesn't back to previous screen

reactjs - 如何扩展 React 函数组件 Prop 类型?

reactjs - 创建 react 应用程序 RangeError : Maximum call stack size exceededat Object. mkdirSync

javascript - 如果状态改变, react 会破坏组件中的所有旧 dom 吗?