[英]Why doesn't Typescript infer return values correctly when possible return object types are specifically defined?
我试图了解 Typescript 如何从 function 调用中推断返回值。 假设我有一个名为sendRequest
的 function 可以返回两个特定格式的对象。 为什么 Typescript 不能知道如果loading
是true
, data
唯一可能的值是null
,如果loading
是false
, data
唯一可能的值是Data
类型? 它仍然说data
可能是null
即使根据列出的可能返回类型这是不可能的。
type Data = { firstName: string; lastName: string };
type ReturnType =
| { loading: true; data: null }
| { loading: false; data: Data };
const sendRequest = (fetch: boolean): ReturnType => {
if (fetch) {
return { loading: true, data: null };
}
return { loading: false, data: { firstName: 'Bart', lastName: 'Simpson' } };
};
const { loading, data } = sendRequest(true);
if (loading) {
data; // <-- Typescript says that `data` can be either `Data` or `null`, while based on the return type, and since `loading` if `true`, `data` can't be `null`.
}
在您解构变量之前,这将作为一个有区别的联合。 TypeScript 可以理解 union 的数据类型取决于loading
的值,但是一旦将其分成两个变量,它就不会保留此信息。
const ret = sendRequest(true);
if (!ret.loading) {
ret.data; // <-- This is now of type Data, not null.
}
正如jcalz在评论中指出的那样,您请求的行为被跟踪为microsoft/TypeScript#30581 。 (感谢jcalz!)
首先值得注意的是,您不想使用ReturnType
作为自定义类型名称,因为从 TypeScript 2.8 开始,它实际上具有保留用途。
但是要回答您的问题: TypeScript 抱怨的原因是因为您就是这样指定返回类型的。 当loading
为true
时, data
为null
:
type Response =
| { loading: true; data: null }
| { loading: false; data: Data };
事实上,我很惊讶 TypeScript 甚至将其键入为Data | null
Data | null
而不是单独的null
。 在 TS Playground 中确实如此:
只是让你知道。 现在可以了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.