【发布时间】:2020-02-25 06:12:40
【问题描述】:
以下代码在使用 TypeScript 编译时会抛出错误。
import React, { SFC } from "react"
import { Link } from "react-router-dom"
import { HashLink } from "react-router-hash-link"
import MarkdownToJSX from "markdown-to-jsx"
interface AnchorProps {
baseUrl: string
relativeUrl: string
href: string
}
const Anchor: SFC<AnchorProps> = function(props) {
/*
FYI, props.baseUrl and props.relativeUrl is used by code I didn’t include in
this example to keep things simple.
*/
if (
props.href.match(/^http(s)?:\/\//) ||
props.href.match(/^mailto:/) ||
props.href.match(/^tel:/)
) {
return (
<a href={props.href} rel="noopener noreferrer" target="_blank">
{props.children}
</a>
)
} else if (props.href.match(/^#/)) {
return (
<HashLink to={props.href} smooth>
{props.children}
</HashLink>
)
} else {
return <Link to={props.href}>{props.children}</Link>
}
}
const Markdown = function() {
return (
<MarkdownToJSX
options={{
overrides: {
a: {
component: Anchor,
props: {
baseUrl: "/privacy-guides",
relativeUrl: "",
},
},
},
}}
>
# This is [markdown](markdown)
</MarkdownToJSX>
)
}
export default Markdown
/Users/sunknudsen/Sites/sunknudsen/sunknudsen-website/src/Test.tsx
TypeScript error in /Users/sunknudsen/Sites/sunknudsen/sunknudsen-website/src/Test.tsx(40,13):
No overload matches this call.
Overload 1 of 2, '(props: Readonly<MarkdownProps>): Markdown', gave the following error.
Type 'FunctionComponent<AnchorProps>' is not assignable to type 'string | SFC<{}> | ComponentClass<{}, any>'.
Type 'FunctionComponent<AnchorProps>' is not assignable to type 'SFC<{}>'.
Types of parameters 'props' and 'props' are incompatible.
Type '{ children?: ReactNode; }' is not assignable to type 'PropsWithChildren<AnchorProps>'.
Type '{ children?: ReactNode; }' is missing the following properties from type 'AnchorProps': baseUrl, relativeUrl, href
Overload 2 of 2, '(props: MarkdownProps, context?: any): Markdown', gave the following error.
Type 'FunctionComponent<AnchorProps>' is not assignable to type 'string | SFC<{}> | ComponentClass<{}, any>'.
Type 'FunctionComponent<AnchorProps>' is not assignable to type 'SFC<{}>'. TS2769
38 | overrides: {
39 | a: {
> 40 | component: Anchor,
| ^
41 | props: {
42 | baseUrl: "/privacy-guides",
43 | relativeUrl: "",
我不明白为什么。
【问题讨论】:
-
这个问题是特定于 React 等特定库的吗?如果是这样,那么它可能应该被标记为这样。如果没有,那么请考虑将上述代码编辑为minimal reproducible example,可以将其放入独立的 IDE 以演示问题,并且仅演示您遇到的问题。现在缺少一些类型定义(
ReactNode等)。 -
我猜这是因为
FunctionComponent<P>是一种函数类型,其中P出现在逆变位置,因此它不是协变的,即FunctionComponent<B>不是FunctionComponent<A>的子类型当B是A的子类型时。但是我不知道这段代码中使用的 React 类型,所以我不知道这是否是一个完整的答案。 -
那一行是call signature。您可以将
(a: A) => B视为{ (a: A): B }的简写形式;后一种形式允许您添加其他属性。 -
一个 React 函数式组件只是一个接受 props 并返回一个 react 元素的函数。函数参数的行为是逆变的..所以你得到了错误,但我相信 jcalz 很快就会回答它:)
-
@sunknudsen 创建一个示例,当我将该示例粘贴到本地文本编辑器中时,将显示错误。如果该示例需要我在本地安装
@types/react也没关系。照原样,当我将您的示例粘贴到本地文本编辑器中时,没有错误。一个很好的例子是不超过 20 行代码。
标签: reactjs typescript