简体   繁体   English

打字稿中的条件返回类型

[英]Conditional return types in typescript

I'm trying to loop over an array of functions (doing network calls) that return different types of configuration objects.我试图循环返回不同类型的配置对象的函数数组(执行网络调用)。 Based on this configuration I'm rendering react components with different props.基于此配置,我正在渲染具有不同道具的反应组件。 But I'm struggling to get typescript to co-operate in this.但我正在努力让打字稿在这方面进行合作。

Here's a simplified example of what I had so far;这是迄今为止我所拥有的一个简化示例;

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);
});

Whenever I loop over the array of config functions and call it, It seems to complain that none of the properties defined on the ConfigObject are present.每当我遍历配置函数数组并调用它时,它似乎抱怨ConfigObject上定义的任何属性都不存在。 Any tips/guidance here?这里有任何提示/指导吗?

在此处输入图片说明

This is expected behavior.这是预期的行为。 Your ConfigObject is either FirstConfig or SecondConfig .您的ConfigObjectFirstConfigSecondConfig Before accessing their distinct properties you must resolve their type or if the property exists in that type.在访问它们不同的属性之前,您必须解析它们的类型,或者该属性是否存在于该类型中。

There are different ways you can achieve this.有多种方法可以实现这一点。

  1. Define a custom type guard for checking a type.定义用于检查类型的自定义类型保护。

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

sandbox link 沙盒链接

  1. Check if property exists in the object检查对象中是否存在属性
const config = getConfig();
if ("a" in config) {
  // the config is of FirstConfig type here
}
  1. Add a common property for all config types by which you can verify it's type为所有配置类型添加一个公共属性,您可以通过它来验证它的类型
type FirstConfig = {
  type: "first";
  a: "a";
};

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

then you can check types like this然后你可以检查这样的类型

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

sandbox 沙盒

  1. Have a type for all configurations with properties set as optional具有所有配置的类型,其属性设置为可选
type ConfigObject = {
  a?: "a";
  b?: "b";
};

In this case you can write your initial code:在这种情况下,您可以编写初始代码:

  const { a, b } = getConfig();

  console.log({ a, b });

sandbox 沙盒

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM