使用流类型构建反应项目以实现最佳类型可重用性

Structuring react project with flow type for best type reusability

我遇到了一个问题,我必须在 store / view 中重新键入/重新定义重复类型/ components 文件,即考虑一个接受一些存储值并具有改变该值的函数的视图,并将该函数传递给组件。

这里有很多类型的可重用性,我继续研究如何为此构建项目,但没有发现任何有用的东西。我发现的是 $PropertyType 实用程序 class,这让我采用了以下方法

// @flow
import React, {Component}
import OtherComponent from "./OtherComponent"

export type MyComponentProps = {
  something: string
}

export type MyComponentState = {
  something2: boolean
}

export type MyComponentActions = {
  check: (
    something2: $PropertyType<MyComponentState, 'something2'>,
    something: $PropertyType<MyComponentProps, 'something'>
  ) => string
}

class MyComponent extends Component<MyComponentProps, MyComponentState> {

  state = { something: /* comes from somewhere else i.e store */ false }

  check: $PropertyType<MyComponentActions, 'check'> = (something2, something) => something2 ? "Default" : something

  render() {
    return <OtherComponent foo={this.check} />
  }
}

这是一个有点无用的例子,但它显示了我选择的模式,这样 OtherComponent 可以导入这些类型,即对于 check 函数并在其中使用 $PropertyType 时它正在指定其 foo 道具类型。

它有效,但非常冗长,因此我想向社区征求替代建议。

我的主要目标是能够重新使用这些类型,而无需以干净的方式重新键入它们。

我不认为这个问题有一个普遍的答案,我不能在这里给你一个明确的答案。我现在已经广泛使用 Flow 工作了 1.5 年,现在还与 React 一起工作了一年。以下是使用类型的一些提示。

1.使用类型推断

Flow 在推断类型方面非常强大。结合以下提示,您可以避免做很多注释。 Flow 只会弄清楚事情是否有效。您还可以使用 typeof 注释来获取值的类型。

2。使用类型而不是组件的接口为您的域建模

这已经在评论中提到了。使用类型为您的域建模。例如。如果您使用显示用户的组件,请为用户对象建模,而不是为组件的界面建模。然后您可以在使用它的组件中导入用户类型。

type User = { id: string, name: string };
type ProfilePropType = { user: User };

class Profile extends Component<ProfilePropType> {
  // ...
}

3。使用状态管理

例如,Redux 可以帮助您处理此处的类型。这将为您提供域类型的结构,并减少传递的道具数量。另一个祝福是 GraphQL 和 Apollo Client / Relay。

4.以编程方式生成类型

我们在后端通过 postloader 从我们的 Postgres 模式生成类型,在前端为我们的 GraphQL 查询生成类型。目前我们正致力于从他们的文档中为 react-semantic-ui 生成类型。之后就没有多少类型可以自己写了。可能有一些工具适合您的用例。

最后一件事:

类型很冗长。有时候直截了当是件好事。这个想法是,类型通过强迫你明确说明事情来减少你花在搜索错误上的时间。通常可以重新定义事物。这也会导致比使用 $PropertyType 更好的错误,因为 Flow 会给你两种不兼容的类型,而不是神秘的消息。