我有这段代码
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>
但是我不能正确地声明类型。
在此版本中,出现以下错误:
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'.
如果我将变量声明更改为
let anchorRenderer: string => React.Component | undefined;
我得到了这个错误
Error:(658, 35) TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.
如何修复类型声明?
答案 0 :(得分:1)
更改
let anchorRenderer: string => React.Component | undefined;
到
let anchorRenderer: (str: string) => React.Component | undefined;
您不能省略参数名称(https://github.com/Microsoft/TypeScript/issues/3693),也必须在类型声明中使用括号(与js箭头功能相反)。