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

jbs*_*ssm 25 javascript reactjs flowtype react-native

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

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

const StationDetail = ({ station }) => {
  const {
    code,
    label,
  } = station;
Run Code Online (Sandbox Code Playgroud)

station是一个JSON响应codelabelstrings其内部JSON.

如何修复错误/警告?

Joh*_*ohn 39

我会写这个

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

function StationDetail({ station } : {station : StationType}) => {
  const {
    code,
    label,
} = station;
Run Code Online (Sandbox Code Playgroud)

有必要声明函数接受的对象参数的类型.


aij*_*aij 7

我尝试了你的例子No errors!,因为Flow不需要私有函数的类型注释.

如果相反我添加export这样的:

// @flow
export const StationDetail = ({ station }) => {
  const {
    code,
    label,
  } = station;
  return code + label;
};
Run Code Online (Sandbox Code Playgroud)

我收到以下错误.(我认为这与你所看到的相近.)

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


Found 1 error
Run Code Online (Sandbox Code Playgroud)

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

export const StationDetail =
  ({ station }: { station: { code: number, label: string } }) =>
Run Code Online (Sandbox Code Playgroud)

要么

export const StationDetail =
  ({ station }: {| station: {| code: string, label: string |} |}) =>
Run Code Online (Sandbox Code Playgroud)

甚至

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) =>
  ...
Run Code Online (Sandbox Code Playgroud)

如果你想确保StationDetail始终使用正确的Radio对象调用,即使当前实现仅查看该station字段.

另一种方法是将第一个注释更改为,// @flow weak并让Flow推断它自己的参数类型.这是Less Good™,因为它可以更容易地意外更改您的公共API并使您的实际意图不那么清晰.