javascript - 打字稿:类型“未定义”不能用作索引类型.ts(2538)
问题描述
我正在尝试学习打字稿,但我似乎不知道如何修复错误Type 'undefined' cannot be used as an index type.ts(2538)
,保持默认道具值。
代码:
interface PVIconInterface {
name: string;
size?: string;
color?: string;
rotate?: number
};
// Styled Components
const IconContainer: any = styled.span <{ $fontSize: string, $colorPath: string, $transform: string, theme: any }>`
display: inline-block;
color: ${({ $colorPath, theme }) => getColor($colorPath, theme)};
font-size: ${({ $fontSize }) => $fontSize};
transform: ${({ $transform }) => $transform};
`;
const PVIcon: React.FC<PVIconInterface> = ({ name, size, color, rotate }) => {
return (
<IconContainer
className={`icon-${name}`}
$colorPath={IconColorMap[color]} //--- this is where TS gives error coz possible undefined
$fontSize={IconSizeMap[size]}
$transform={getTransformStyles(rotate)}
/>
);
};
PVIcon.defaultProps = {
color: 'normal',
size: 'small',
rotate: 0
};
export default PVIcon;
任何指针都非常感谢!谢谢
解决方案
Typescript 编译器对 defaultProps 一无所知。所以它抱怨颜色道具可能是未定义的(正如它在 PVIconInterface 中声明的那样)。
可能的解决方案
将默认道具逻辑移动到解构默认值中,如下所示:
...
const PVIcon: React.FC<PVIconInterface> = ({
name,
size = "small",
color = "normal",
rotate = 0,
}) => {
return
...
如果您希望看到其他或更复杂的解决方案,请参考一篇关于 defaultProps 和 TypeScript 的好文章:medium article
附言。这是我的第一个堆栈答案,所以如果我犯了错误,请纠正我:)
推荐阅读
- javascript - Bootstrap 4.5.2 错误/更新 popper.js 过时的新方法是 popperjs/core
- django - Django没有重新连接到数据库?
- high-availability - 带起搏器的地理集群 - 仲裁与展位
- flutter - 摆脱 Flutter UI 中的双下划线
- c++ - 使用计时器和按钮编码 arduino 交通灯
- flutter - 在颤振中通过蓝牙将字符串值从一个智能手机设备发送到另一台智能手机设备
- html - 删除网页内容下方的空白
- c++ - 在 C++ 类中存储动态数据量
- java - Java 日历未显示正确的 HOUR_OF_DAY
- excel - 将多个 excel 工作簿从一个文件转换为 pdf - 只有未隐藏的工作表