【发布时间】:2021-03-11 08:27:41
【问题描述】:
我正在使用打字稿反应。
xs,sm,md,lg 在 props 中传递。
每个尺寸(14px、16px、18px、24px)的 px 被传递给 Icon。
(1)中的错误显示在fontSize={FONTSIZE[size]}的地方。
错误
①Type 'undefined' cannot be used as an index type.ts(2538)
②Type '(string & {} & ("xs" | "sm" | "md" | "lg")) | undefined' does not satisfy the constraint 'string | number | symbol'.
Type 'undefined' is not assignable to type 'string | number | symbol'.ts(2344)
import React from 'react';
import { Link as ChakraLink, LinkProps } from '@chakra-ui/react';
import { FunctionComponent } from 'react';
import { OpenExternalIcon } from './Icon/OpenExternalIcon';
export type AtomLinkProps = LinkProps & {
iconType?: 'openExternal';
size?: 'xs' | 'sm' | 'md' | 'lg';
};
const FONTSIZE: Record<AtomLinkProps['size'], string> = {
xs: '14px',
sm: '16px',
md: '18px',
lg: '24px',
};
export const Link: FunctionComponent<AtomLinkProps> = ({
size,
iconType,
children,
...props
}) => {
const Icon: Record<'openExternal', JSX.Element> = {
openExternal: <OpenExternalIcon fontSize={FONTSIZE[size]} />,
};
return (
<ChakraLink size={size} {...props}>
{children}
{Icon[iconType!]}
</ChakraLink>
);
};
图片④ 错误消息
Element implicitly has an 'any' type because expression of type '"lg" | ({} & "xs") | ({} & "sm") | ({} & "md")' can't be used to index type 'Record<FontSizeType, string>'.
【问题讨论】:
-
原因可能是 size 是可选的并且可以是未定义的。尝试删除“?”在类型定义中的大小之后。
-
好吧,正如错误提示的那样, undefined 不能用作索引类型。 Size 是一个可选属性,因此它可以是未定义的。
-
请勿发布图片或您的代码或错误消息。以文本形式包含它们
-
对不起。我应该把 cmets 的代码放在哪里?
标签: reactjs typescript chakra