首页 > 解决方案 > 打字稿错误类型'字符串| undefined' 不满足约束 'string | 号码 | 象征'

问题描述

我正在使用打字稿,反应。
当 xs、sm、md、lg 之一在 props 中传递时,我想调整每个 px 大小。
我按如下方式使用记录,但出现打字稿错误。

错误

Type 'string | undefined' does not satisfy the constraint 'string | number | symbol'.
  Type 'undefined' is not assignable to type 'string | number | symbol'.ts(2344)
export type IconProps = {
  fontSize?: 'xs' | 'sm' | 'md' | 'lg';
  padding?: number;
  margin?: number;
};

export const FONTSIZE: Record<IconProps['fontSize'], string> = {
  xs: '14px',
  sm: '16px',
  md: '18px',
  lg: '24px',
};

①</p>

import { Icon } from '@chakra-ui/react';
import React from 'react';
import { IconProps, FONTSIZE } from '../theme/iconProps';


export const ArrowRightIcon: React.FunctionComponent<IconProps> = ({
  fontSize,
  ...props
}) => {
  return (
    <Icon fontSize={FONTSIZE[fontSize]} {...props}>
      <path d="" /> // Abbreviation
    </Icon>
  );
};

标签: reactjstypescript

解决方案


fontSize?: 'xs' | 'sm' | 'md' | 'lg';

此处可能的值之一是undefined,因为?这使它成为可选的。但undefined不能是对象的键,因此当您尝试使用这些作为键进行记录时,打字稿会抱怨。

您可以undefined使用NonNullable排除:

export const FONTSIZE: Record<NonNullable<IconProps['fontSize']>, string> = {
  xs: '14px',
  sm: '16px',
  md: '18px',
  lg: '24px',
};

或者,如果您愿意,排除是另一种选择:

export const FONTSIZE: Record<Exclude<IconProps['fontSize'], undefined>, string> = {
  xs: '14px',
  sm: '16px',
  md: '18px',
  lg: '24px',
};

游乐场链接


推荐阅读