【问题标题】:Conditional return types in typescript打字稿中的条件返回类型
【发布时间】:2021-10-25 15:29:12
【问题描述】:

我正在尝试遍历返回不同类型配置对象的函数数组(进行网络调用)。基于此配置,我正在渲染具有不同道具的反应组件。但我正在努力让打字稿在这方面合作。

这是我目前所拥有的一个简化示例;

type FirstConfig = {
  a: 'a';
};

type SecondConfig = {
  b: 'b';
};

type ConfigObject = FirstConfig | SecondConfig;
type ConfigFunction = () => ConfigObject;
const configArray: ConfigFunction[] = [() => ({ a: 'a' }), () => ({ b: 'b' })];

configArray.map(getConfig => {
  const { a, b } = getConfig();
  console.log(a, b);
});

每当我遍历配置函数数组并调用它时,似乎都抱怨ConfigObject 上定义的属性都不存在。这里有任何提示/指导吗?

【问题讨论】:

  • 您需要测试返回对象的类型。使用|,对象将仅具有可用的公共属性而不会缩小类型。

标签: javascript reactjs typescript


【解决方案1】:

这是预期的行为。 您的ConfigObjectFirstConfigSecondConfig。在访问它们的不同属性之前,您必须解析它们的类型或者该属性是否存在于该类型中。

您可以通过多种方式实现这一目标。

  1. 定义用于检查类型的自定义类型保护。

const isFirstConfig = (config: ConfigObject): config is FirstConfig => !!(config as any).a;

sandbox link

  1. 检查对象中是否存在属性
const config = getConfig();
if ("a" in config) {
  // the config is of FirstConfig type here
}
  1. 为所有配置类型添加一个通用属性,您可以通过该属性验证其类型
type FirstConfig = {
  type: "first";
  a: "a";
};

type SecondConfig = {
  type: "second";
  b: "b";
};

然后你可以检查这样的类型

const config = getConfig();
if (config.type === "first") {
  console.log("first type");
  // config is FirstConfig type in this 'if' block
}

sandbox

  1. 为所有配置设置一个类型,并将属性设置为可选
type ConfigObject = {
  a?: "a";
  b?: "b";
};

在这种情况下,您可以编写初始代码:

  const { a, b } = getConfig();

  console.log({ a, b });

sandbox

【讨论】:

  • 感谢您的扩展回复和代码示例!根据类型参数切换配置似乎是最干净的。打算这样做:)
猜你喜欢
  • 2021-09-18
  • 2021-09-17
  • 2022-07-07
  • 2021-10-22
  • 2019-10-25
  • 2019-05-30
  • 2020-06-29
  • 2019-05-03
  • 1970-01-01
相关资源
最近更新 更多