reactjs - 打字稿错误类型'字符串| 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>
);
};
解决方案
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',
};
推荐阅读
- twilio - 在 Twilio Studio 流之间传递用户
- ios - Xamarin iOS:如何从文件路径加载 WebP
- java - 是否有一种方法可以创建名称等于变量当前状态的对象
- python-3.x - 如何找出一个集群在 PCA 双图上代表什么?
- html - 使用 CSS 网格定位
- bash - 如何使用 sed 从网页中提取文本
- php - “长时间运行”PHP 脚本使用“header(“Location: $url”);“重定向状态代码:500”失败
- c - C中的数组越界
- filemaker - 什么公式可以识别奇数和偶数
- wpf - GridView 标题行上的 ContextMenu(右键单击)