Anthony Kong
Anthony Kong

Reputation: 40754

What is a correct type for a nullable function variable in typescript?

I have this bit of code

let anchorRenderer: string => React.Component;  // line 658
if (link) {
    if (userAnchorRenderer) {
      anchorRenderer = userAnchorRenderer;  // line 661
    } else {
      anchorRenderer = (link: string) => <a className={styles.link} href={link}/>    // line 663
    }
}

...

// Usage of the function 
return <div>
    {anchorRenderer && anchorRenderer(link)})   
 </div>

But I am not able to get the type declaration right.

In this version, I got these errors:

Error:(663, 11) TS2322: Type 'P["anchorRenderer"]' is not assignable to type 'string'.
  Type '((link: string) => Component<{}, {}, any>) | undefined' is not assignable to type 'string'.
    Type 'undefined' is not assignable to type 'string'.
Error:(663, 11) TS2322: Type '(link: string) => Element' is not assignable to type 'string'.

If I changed the variable declaration to

let anchorRenderer: string => React.Component | undefined;

I got this error instead

Error:(658, 35) TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.

How can I fix the type declaration?

Upvotes: 0

Views: 157

Answers (1)

Nurbol Alpysbayev
Nurbol Alpysbayev

Reputation: 21931

Change

let anchorRenderer: string => React.Component | undefined;

to

let anchorRenderer: (str: string) => React.Component | undefined;

You cannot omit a parameter name (https://github.com/Microsoft/TypeScript/issues/3693), also you have to use parens in a type declaration (in contrast to js arrow function).

Upvotes: 1

Related Questions