如何纠正流程警告:解构(缺少注释)

How to correct flow warning: destructuring (Missing annotation)

我正在编写一个小型 React Native 应用程序,我正在尝试使用 Flow,但我真的无法在任何地方获得关于它的适当教程。

我不断收到错误:destructuring (Missing annotation) 关于此代码第一行中的 ({ station })

const StationDetail = ({ station }) => {
  const {
    code,
    label,
  } = station;

stationjson 响应 并且 codelabelstringsjson.

如何修复 error/warning?

为了对象解构工作,您应该在赋值的右侧提供适当的对象结构。在这种特殊情况下,{station} 作为函数参数(赋值的左侧)应该由 {station:{code: "stg", label:"stg"}} 之类的东西提供。确保您使用适当的对象作为参数调用 StationDetail 函数,例如

var StationDetail = ({ station }) => {
  var {code, label} = station;
  console.log(code,label);
},
    data = {station: {code: 10, label:"name"}};

StationDetail(data);

我会这样写

type StationType = {
  code: String,
  label: String,
}

function StationDetail({ station } : {station : StationType}) => {
  const {
    code,
    label,
} = station;

需要声明函数接受的对象参数的类型。

我尝试了你的示例并得到了 No errors!,因为 Flow 不需要对私有函数进行类型注释。

如果我添加一个 export 像这样:

// @flow
export const StationDetail = ({ station }) => {
  const {
    code,
    label,
  } = station;
  return code + label;
};

我收到以下错误。 (我认为这与您所看到的足够接近。)

Error: 41443242.js:2
  2: export const StationDetail = ({ station }) => {
                                   ^^^^^^^^^^^ destructuring. Missing annotation


Found 1 error

您至少可以通过两种方式解决该问题。更好的方法是为函数参数添加类型注释。例如:

export const StationDetail =
  ({ station }: { station: { code: number, label: string } }) =>

export const StationDetail =
  ({ station }: {| station: {| code: string, label: string |} |}) =>

甚至

type Code = 1 | 2 | 3 | 4 | 5 | 6;
type Radio ={|
  station: {| code: Code, label: string |},
  signalStrength: number,
  volume: number,
  isMuted: bool,
|};
export const StationDetail = ({ station }: Radio) =>
  ...

如果您想确保 StationDetail 始终使用正确的 Radio 对象调用,即使当前的实现只查看 station 字段。

另一种选择是将第一个注释更改为 // @flow weak 并让 Flow 自行推断参数类型。这是 Less Good™,因为它更容易意外更改您的 public API 并使您的实际意图不那么明确。