首页 > 解决方案 > 试图将 calc 应用程序转换为打字稿,这个函数应该是什么类型?

问题描述

我现在已经编辑添加我的按钮组件

    import React, {FC} from 'react';
    import '../styling/button.css';

    // create types for props
    type ButtonProps = {
      // HandleClick needs to a be a function type with a parameter that takes a ReactNode (since that's the type of props.children in this case, and you want to pass it into that function
      handleClick: (children: React.ReactNode) => void; // basically, clicking the reusable component I made, the arg is a ReactNode 
      // don't need to specify children prop, <ButtonProps> has it by default
    }

                    // set type for value
    const isOperator = (val: React.ReactNode) => {
      // isNaN() only takes a number parm, and only checks whether a number is set to specal value of 'NaN'
      return (typeof val === "number" && !isNaN(val)) || val === "." || val === "=";
    }

    // generic type, FC
    export const Button: FC <ButtonProps> = ({children, handleClick}) => {
      return (
        <div className={`button-wrapper ${isOperator(children) ? null : "operator"}`}
            onClick={() => handleClick(children)}
        >
          {children}
        </div>
      )
    }

标签: reactjstypescript

解决方案


是的,这就是你在这个组件中所需要的。Typescpript 能够根据使用情况推断很多。例如,您不需要声明您input的状态是 a string,因为它根据初始值的类型假设它""

此代码中的打字稿类型存在问题,但它们将出现在您的Button组件上。 Button正在接收一个handleClick以 anumber作为参数的函数。那样行吗?您如何处理单击*按钮?你如何调用一个只能接受的函数number

如果我们的按钮确实接受了我们提供的道具,那么它看起来像这样:

interface ButtonProps {
  handleClick: (val: number) => void;
  children: ReactNode; // this is the default so it's not actually needed here
}

const Button: React.FC<ButtonProps> = ({ handleClick, children }) => (
  <button onClick={() => handleClick(children)}>{children}</button>
);

调用时会报错handleClick(children)

'ReactNode' 类型的参数不能分配给'number' 类型的参数。

类型“未定义”不可分配给类型“数字”

好的,所以我们不能允许任何children. 如果我们添加{children: number;}ButtonPropsthen 中修复错误Button但在中创建一个新错误App

“按钮”组件不接受文本作为子元素。

所以我们需要将childrenprop 读取为string. 我们的Button会是这样的:

interface ButtonProps {
  handleClick: (val: string) => void;
  children: string;
}

const Button: React.FC<ButtonProps> = ({ handleClick, children }) => (
  <button onClick={() => handleClick(children)}>{children}</button>
);

现在我们在 App 中得到一个不同的错误:

类型 '(val: number) => void' 不可分配给类型 '(val: string) => void'

这给我们带来了完整的循环。我们只需更改handleClick函数的类型,就完成了!

const handleClick = (val: string) => {
  setInput(input + val);
};

代码沙盒链接


推荐阅读