[英]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
.您的
ConfigObject
是FirstConfig
或SecondConfig
。 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.有多种方法可以实现这一点。
const isFirstConfig = (config: ConfigObject): config is FirstConfig => !!(config as any).a;
const config = getConfig();
if ("a" in config) {
// the config is of FirstConfig type here
}
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
}
type ConfigObject = {
a?: "a";
b?: "b";
};
In this case you can write your initial code:在这种情况下,您可以编写初始代码:
const { a, b } = getConfig();
console.log({ a, b });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.