转换打字稿反应计算器按钮组件

convert typescript react calculator button component

关于您所指出的代码,有几点需要指出:

const isOperator: number | string = (val) => {
  return !isNaN(val) || val === "." || val === "=";
};

  • 您输入的 isOperatornumberstring, 但是您随后为其分配了一个功能。这就是为什么您会收到“此表达式不可调用”的原因 - 因为您已经告诉 TypeScript 该变量是 numberstring - 它们都不可调用。我怀疑你 的意思是 将这些类型分配给 val 参数
  • isNaN(...) 只需要一个 number 参数,所以当您进行上述更正时,您会发现这里出现了进一步的类型错误。这是一个合理的错误,因为 if isNaN 的工作是检查 number 是否设置为特殊值 NaN,因此您需要更正逻辑以缩小类型第一

要解决这些问题,您可以这样做:

const isOperator = (val: number | string) => {
  return (typeof val === "number" && !isNaN(val)) || val === "." || val === "=";
};

在你的道具旁边:

type ButtonProps = {
  handleClick: any;
  children: any;
};

  • 您不需要指定 children 道具:因为您正在使用 FC<ButtonProps>,所以 children 道具已经存在。
  • HandleClick 需要是一个函数类型,其参数采用 ReactNode(因为在这种情况下这是 props.children 的类型,并且您想将其传递给该函数

所以这给你留下了这个:

type ButtonProps = {
  handleClick: (children: React.ReactNode) => void;
};

所以你现在到了那里,但是打字稿不会接受这个,因为实际上 props.childrenReact.ReactNode 类型(不仅仅是 string | number)所以当你尝试传给isOperator,会报类型错误。

幸运的是,React.ReactNodenumber | string 兼容(因为它是 just a union type which contains those options,所以您只需将 isOperator 更改为以下内容:

const isOperator = (val: React.ReactNode) => {
  return (typeof val === "number" && !isNaN(val)) || val === "." || val === "=";
};

完成最后一次更改后,您的代码应该可以编译。