我有一个类型 export type status = 'success' | 'error' | undefined;
现在,有一个对象映射到一个图标
const iconsMap: Record<status, React.ReactSVGElement> = {
error: ErrorIcon,
success: SuccessIcon,
};
在这里,由于undefined
iconsMap中没有键,因此会导致打字错误
Type 'string | undefined' does not satisfy the constraint 'string | number | symbol'. Type 'undefined' is not assignable to type 'string | number | symbol'.
我该如何解决?
您可以排除undefined
使用NonNullable实用程序:
const iconsMap: Record<NonNullable<status>, React.ReactSVGElement> = {
error: ErrorIcon,
success: SuccessIcon,
};
并正式收到错误不是因为没有键undefined
,而是因为Record
具有通用类型约束并且仅接受string | number | symbol
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句