返回为字符串或数字的函数参数或返回字符串或数字的函数

时间:2018-11-27 21:56:13

标签: reactjs typescript typescript-typings higher-order-components typescript-types

我正在使用TypeScript构建React应用。

我正在尝试定义一个函数(用于HOC),该函数带有一个称为value的参数,该参数可以是字符串或数字,也可以是返回字符串或数字的函数。

所以我尝试的是:

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是什么?

1 个答案:

答案 0 :(得分:1)

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

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

编辑:如果您希望这两种函数类型接受可选参数,即WrappedComponent道具,则必须导入代表该道具的接口。组件(如果它们不在范围内),并在其中使用问号?,以使TS知道它是可选的。

import { WrappedComponentProps } from './WrappedComponent';

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