我正在尝试将React中的一个简单的自定义Link组件转换为使用TypeScript。
以下是JavaScript中的简单链接组件:
import React from "react";
import { Link as RouterLink } from "react-router-dom";
import styled from "@emotion/styled";
const StyledLink = styled(RouterLink)`
color: blue;
`;
const StyledAnchor = styled.a`
color: red;
`;
export default function Link(props) {
return Boolean(props.to) ? (
<StyledLink {...props} />
) : (
<StyledAnchor {...props} />
);
}
以下是上述组件的用法:
import React from 'react'
import Link from 'components/Link'
export default function Demo() {
return (
<>
<Link href="https://stackoverflow.com">external link</Link>
<br />
<Link to="/">internal link</Link>
</>
)
}
但是我在将上面的Link组件转换为使用TypeScript时遇到了问题。
以下是我迄今为止在TypeScript:中的内容
import { AnchorHTMLAttributes } from 'react'
import { Link as RouterLink, LinkProps } from 'react-router-dom'
import styled, { StyledComponent } from '@emotion/styled'
import { EmotionJSX } from '@emotion/react/types/jsx-namespace'
type AnchorProps = AnchorHTMLAttributes<HTMLAnchorElement>
const StyledLink: StyledComponent<LinkProps> = styled(RouterLink)`
color: blue;
`
const StyledAnchor: StyledComponent<AnchorProps> = styled.a`
color: red;
`
export default function Link(
props: LinkProps | AnchorProps
): EmotionJSX.Element {
if (/* HOW TO CHECK IF props IS LinkProps or AnchorProps */) {
return <StyledLink {...props} />
} else {
return <StyledAnchor {...props} />
}
}
那么,如何在Typescript中找出props
是类型LinkProps
还是类型AnchorProps
呢?我已经尝试过instanceof
,但出现错误'LinkProps' only refers to a type, but is being used as a value here
:
export default function Link(
props: LinkProps | AnchorProps
): EmotionJSX.Element {
if (props instanceof LinkProps) {
return <StyledLink {...props} />
} else {
return <StyledAnchor {...props} />
}
}
TypeScript不允许您直接进行instanceof
检查,但您可以使用一个技巧来获得所需内容。LinkProps
是一个需要存在某些字段的接口,而AnchorProps
需要不同的字段。因此,如果您检查是否存在to
(一个仅存在于LinkProps
上的字段(,则TypeScript将知道,如果检查成功,则props
是LinkProps
,如果检查失败,则props
是AnchorProps
。
因此,对于你的例子,你可以写:
export default function Link(
props: LinkProps | AnchorProps
): EmotionJSX.Element {
if ('to' in props) {
return <StyledLink {...props} />
} else {
return <StyledAnchor {...props} />
}
}