为字符串或数字的函数参数或 returns 为字符串或数字的函数

Function paramater that is either a string or a number or a function that returns either a string or a number

我正在使用 TypeScript 构建一个 React 应用程序。

我正在尝试定义一个函数(对于 HOC),它接受一个名为 value 的参数,它可以是字符串、数字或 returns 的函数字符串或数字。

所以我尝试的是:

const myHOC = (
  value: string | number | () => string | () => number
) => WrappedComponent => // ...

但是 TSLint 抱怨第二个 | 之后的所有内容(所以基本上是关于两个函数)。

它说:

[ts] Type expected. [1110]

(),

[ts] ',' expected. [1005]

对于 =>

[ts] 'string' only refers to a type, but is being used as a value here. [2693]
[tslint] Forbidden bitwise operation [no-bitwise]

分别为string / number

如何告诉 TypeScript value 是什么?

TSLint(以及 TypeScript)无法正确解析它,您可以将您的函数类型包裹在大括号中,让它理解您的目标。

const myHOC = (
  value: string | number | (() => string) | (() => number)
) => WrappedComponent;

编辑:如果你希望这两个函数类型接受一个可选参数,也就是WrappedComponent props,你必须导入对应的接口对于该组件的道具(如果它们不在范围内)并在其中使用问号 ?,让 TS 知道它是可选的。

import { WrappedComponentProps } from './WrappedComponent';

const myHOC = (
  value: string | 
         number | 
         ((props?: WrappedComponentProps ) => string) |
         ((props?: WrappedComponentProps ) => number)
) => WrappedComponent;