【问题标题】:Issue with typing object TypeScript - when using a predefined type with null键入对象 TypeScript 的问题 - 使用带有 null 的预定义类型时
【发布时间】:2020-02-08 17:27:12
【问题描述】:

我有以下type

type Team = 'liverpool' | 'manUtd' | 'arsenal' | null;

然后我有以下对象。

const teams: Record<Team, JSX.Element> = {
  liverpool: <Liverpool />,
  manUtd: <ManU />,
  arsenal: <Arsenal />,
};

如果我使用teams 作为Record 的第一部分,我会看到以下错误:

Type 'Team' does not satisfy the constraint 'string | number | symbol'.
  Type 'null' is not assignable to type 'string | number | symbol'.ts(2344)

如果我使用Record&lt;string, JSX.Element&gt;,它可以正常工作。

【问题讨论】:

  • null 不能用作密钥。为什么你的类型定义中需要null
  • 感谢 @georg 在应用程序的其他地方它可以为空,因为它并不总是存在:-)

标签: javascript reactjs typescript ecmascript-6


【解决方案1】:

Record&lt;NonNullable&lt;Team&gt;, JSX.Element&gt;

如果这有帮助,请告诉我。出现此错误是因为 null 不是有效的 javascript 对象键类型。

【讨论】:

  • 是的,也没有线索。实际上,我认为我的投票不起作用,并且 SO 存在错误 :-D 无论如何,我都会给你绿色的勾号,干杯
【解决方案2】:

Record 的类型是 Record&lt;K extends string | number | symbol, T&gt;

因此,您提供给Record 的第一个类型必须是stringnumbersymbol。您不能将 null 分配给它,因此您的 Team 类型不满足约束。你应该从你的Team 类型中删除null,它会像一个魅力一样工作。

【讨论】:

  • 确实,team: null 没有任何意义。
猜你喜欢
  • 1970-01-01
  • 2019-12-21
  • 2018-05-29
  • 2021-07-26
  • 2016-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-08
相关资源
最近更新 更多