繁体   English   中英

在 TypeScript 中解构 React 钩子数组时,此表达式不可调用

[英]This expression is not callable when destructuring an array of React hooks in TypeScript

在我的 React TS 组件中,我有一堆字段,下面是人为的示例,用于检查特定条件,如果不满足,则将特定字段错误设置为 true,以反映组件 DOM(因此不提交)但是,当我有下面的代码时,它会在setErr function 上抛出一个expression not callable

const App = () => {
  const [name, setName] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [nameError, setNameError] = React.useState(false);
  const [emailError, setEmailError] = React.useState(false);
  return (
    <div className="App">
      <input
        type="text"
        value={name}
        style={{
          border: `1 px solid ${nameError ? "red" : "black"}`
        }}
        onChange={e => {
          setName(e.target.value);
        }}
      />
      <input
        type="text"
        value={email}
        onChange={e => {
          setEmail(e.target.value);
        }}
        style={{
          border: `1 px solid ${emailError ? "red" : "black"}`
        }}
      />
      <button
        onClick={() => {
          const errors = [
            [setNameError, name.length],
            [setEmailError, email.length]
          ];

          let canSubmit = true;
          errors.forEach(validation => {
            const [setErr, condition] = validation;
            console.log(!condition);
            if (!condition) {
              canSubmit = false;
              setErr(true); // <---- ERROR HERE
            }
          });

          if (canSubmit) { /* submit the form */ } 
        }}
      >
        submit
      </button>
    </div>
  );
};

这仅在 TypeScript 中出现错误,因为它在 vanilla/jsx 中运行良好。 并且不能在某些构建系统中编译。

完整的错误是:

This expression is not callable.
  Not all constituents of type 'string | number | boolean | Dispatch<SetStateAction<boolean>>' are callable.
    Type 'string' has no call signatures.

我特别困惑为什么它认为setErr是字符串类型,而它应该等于从 useState 解构的 setNameError function。

您只需将as const添加到errors声明中:

  const errors = [
        [setNameError, name.length],
        [setEmailError, email.length]
   ] as const;

这样,arrays 不会被输入为 arrays 而是作为元组。

推断的errors类型是让您失望的原因。 通过您的错误消息,我们可以得出const errors: (string | number | boolean | Dispatch<SetStateAction<boolean>>)[][] ,因此 typescript 推断数组元素可以是一堆东西,其中一些不是可调用的。 相反,您可以将其对象化,并且推断的类型将分配给键,从而允许您进行解构和正确调用,即

<button
  onClick={() => {
    const errors = [
      {setError:setNameError, condition:name.length},
      {setError:setEmailError, condition:email.length}
    ];

    let canSubmit = true;
    errors.forEach(validation => {
      const {setError, condition} = validation;
      console.log(!condition);
      if (!condition) {
        canSubmit = false;
        setError(true); // <---- ERROR HERE
      }
    });

    if (canSubmit) { /* submit the form */ } 
  }}
>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM