我有一个类型
export type status = 'success' | 'error' | undefined;
现在,有一个映射到图标的对象
const iconsMap: Record<status, React.ReactSVGElement> = {
error: ErrorIcon,
success: SuccessIcon,
};
这里,由于iconsMap中没有键undefined
,导致打字错误
Type 'string | undefined' does not satisfy the constraint 'string | number | symbol'. Type 'undefined' is not assignable to type 'string | number | symbol'.
我该如何解决这个问题?
答案 0 :(得分:2)
您可以使用 NonNullable 实用程序排除 undefined
:
const iconsMap: Record<NonNullable<status>, React.ReactSVGElement> = {
error: ErrorIcon,
success: SuccessIcon,
};
正式地,您得到错误不是因为没有键 undefined
,而是因为 Record
具有泛型类型约束并且只接受 string | number | symbol
。