打字稿-类型“未定义”不能分配给类型“字符串”数量 |象征'

时间:2021-01-26 17:41:14

标签: typescript casting

我有一个类型 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'.

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

您可以使用 NonNullable 实用程序排除 undefined

const iconsMap: Record<NonNullable<status>, React.ReactSVGElement> = {
  error: ErrorIcon,
  success: SuccessIcon,
};

正式地,您得到错误不是因为没有键 undefined,而是因为 Record 具有泛型类型约束并且只接受 string | number | symbol