如何接受两种类型的任何一种

时间:2019-07-25 02:42:53

标签: reactjs typescript

我正在尝试处理类型问题。

我具有回调函数属性,其参数在React Functional Component中具有字符串或数字两种类型

Here are some of my favorite games! The Division, WoW, Legend of Zelda, Super Smash Bros.

我想将具有字符串参数的getRegistraionId函数传递给功能组件interface InputProps { getValue?: (value: string | number) => void; } const Input: React.FC<InputProps> = (props) => { ... }

Input

我希望它将被接受,因为getValue的参数具有字符串或数字两种类型,但是

 const getRegistrationId = (registrationId: string) => {
    setRegistrationId(registrationId);
  };

为什么?

2 个答案:

答案 0 :(得分:2)

getRegistrationId 仅接受字符串,但是您的组件想要一个可以接受字符串或数字的函数,这就是为什么它拒绝使用{ {1}}。

您可以:

  • getRegistrationId也接受数字
  • 或者,将getRegistrationId的类型更改为仅接受字符串
  • 或者,作为一种快速技巧,使用getValue

答案 1 :(得分:1)

registrationId类型仅接受string,但getValue可以接受stringnumber。如果您希望getValue接受一个采用某个函数的函数,或者您希望getValue接受一个函数的2个版本。

示例:

type FunctionType = ((value: string) => void) | ((value: number) => void);

const doSomethingWithString: FunctionType = (value: string) => {
  console.log(value);
};
const doSomethingWithNumber: FunctionType = (value: number) => {
  console.log(value);
};