使用参数作为函数严格模式打字稿错误

时间:2019-12-09 07:49:14

标签: reactjs typescript

如果关闭严格的打字稿模式,则下面的代码很好

import * as React from "react";

const Form = ({ add }) => (
  <div
    onClick={() =>
      add({ //warning here
        a: 1,
        b: 2
      })
    }
  >
    Add
  </div>
);

export default Form;

但是它会引发警告(绑定元素“ add”隐含一个“ any”),因为我没有为add function指定类型,没有任何线索解决该问题?

https://codesandbox.io/s/focused-snowflake-0up5q

3 个答案:

答案 0 :(得分:0)

尝试:

const Form = ({ add }: {add: any}) => (

答案 1 :(得分:0)

import * as React from "react";
import { render } from "react-dom";
import Form from "./Form";
import "./styles.css";

function App() {
  const add = ({a,b} : { a: any, b: any}, ) => {
    console.log("a+b", a + b);
  };
  return (
    <div className="App">
      <Form add={add} />
    </div>
  );
}

const rootElement = document.getElementById("root");
render(<App />, rootElement);

答案 2 :(得分:0)

我相信,您应该提供Form组件的类型。 例如,如下所示:

const Form = ({ add }: FormProps) => (/* here is your component implementation /*)

FormProps看起来像这样:

interface FormProps {
  add: (terms: AddTerms) => void
}

/* 
  personally, I don't like to set type of Any,
  and I would set A and B to number explicitly 
  but is a matter of taste
*/
interface AddTerms {
  a: any,
  b: any
}

接下来,在应用程序组件中,为add参数提供类型:

const add = ({ a, b }: {a: any, b: any}) => {
  console.log("a+b", a + b);
};

或从表单组件模块导入AddTerms接口

const add = ({ a, b }: AddTerms) => {
  console.log("a+b", a + b);
};