I'm building a React app using TypeScript.
I'm trying to define a function (for a HOC) that takes in a parameter called value
, which can either be a string, or a number, or a function that returns a string or a number.
So what I tried is:
const myHOC = (
value: string | number | () => string | () => number
) => WrappedComponent => // ...
But TSLint complains about everything that comes after the second |
(so basically about both functions).
It says:
[ts] Type expected. [1110]
for the ()
,
[ts] ',' expected. [1005]
for the =>
and
[ts] 'string' only refers to a type, but is being used as a value here. [2693]
[tslint] Forbidden bitwise operation [no-bitwise]
for the string
/ number
respectively.
How can I tell TypeScript what value
is?
TSLint (as well as TypeScript) can't parse it properly, you could wrap your function types into braces, to let it understand what you aim for.
const myHOC = (
value: string | number | (() => string) | (() => number)
) => WrappedComponent;
Edit: If you wish these two function types to accept an optional parameter, which are the WrappedComponent
props, you'll have to import the interface that stands for the props of that component (if only they are not in scope) and use it inside them with a question mark ?
, to let TS know that it's optional.
import { WrappedComponentProps } from './WrappedComponent';
const myHOC = (
value: string |
number |
((props?: WrappedComponentProps ) => string) |
((props?: WrappedComponentProps ) => number)
) => WrappedComponent;