1

我正在使用打字稿反应。
xs,sm,md,lg 在 props 中传递。
每个尺寸(14px、16px、18px、24px)的 px 被传递给 Icon。(1)中的错误显示在fontSize={FONTSIZE[size]}的地方。
错误 (2) 显示在 <AtomLinkProps['size'], string>。

错误

①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>'.

在此处输入图像描述

4

2 回答 2

0

正如错误所暗示的那样,FONTSIZE 不会将 undefined 视为未定义大小时可能发生的索引。您可以通过size强制组件来解决它,或者提供默认值作为 FONTSIZE 的键

解决方案1:

export type AtomLinkProps = LinkProps & {
  color?: ColorType;
  iconType?: 'openExternal'; 
  // make size aa compulsory attribute rather than optional
  size: 'xs' | 'sm' | 'md' | 'lg';
};

解决方案2:

除了使用 AtomLinkProps 来定义FONTSIZE记录键,您可以使用另一种类型FONTSIZE,然后您可以使用默认值,同时size作为键传递给FONTSIZE

type FontSizeType = 'xs' | 'sm' | 'md' | 'lg';
export type AtomLinkProps = LinkProps & {
  iconType?: 'openExternal';
  size?: FontSizeType;
};
const FONTSIZE: Record<FontSizeType, string> = {
  xs: '14px',
  sm: '16px',
  md: '18px',
  lg: '24px',
};

<OpenExternalIcon fontSize={FONTSIZE[size || 'lg']} />,
于 2021-03-11T08:46:52.603 回答
0

问题就在这里

export type AtomLinkProps = LinkProps & {
  color?: ColorType;
  iconType?: 'openExternal';
  // size is optional so you can not use this property as index 
  size?: 'xs' | 'sm' | 'md' | 'lg';
};

我认为它会解决问题

尺寸:'xs' | 's' | 'md' | 'lg';

于 2021-03-11T08:47:13.843 回答