javascript - Why doesn't Typescript infer return values correctly when possible return object types are specifically defined?
问题描述
I'm trying to understand how Typescript infers the return values from a function call. Say I have a function called sendRequest
that can return two specifically formatted objects. Why isn't Typescript able to know that if loading
is true
, that the only possible value for data
is null
, and that if loading
is false
, the only possible value for data
is a Data
type? It is still saying that data
could be null
even though that's impossible based on the possible return types listed.
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`.
}
解决方案
This works as a discriminated union until you destructure the variables. TypeScript can understand that the data type of the union is conditional on the value of loading
, but it doesn't keep this information once you break it apart into two variables.
const ret = sendRequest(true);
if (!ret.loading) {
ret.data; // <-- This is now of type Data, not null.
}
As jcalz points out in the comments, the behavior you're requesting is tracked as microsoft/TypeScript#30581. (Thanks jcalz!)
推荐阅读
- asp.net-core - 不应为已部署的应用程序 / ASPNETCORE_ENVIRONMENT 启用开发环境
- python - 在 Python 中使用 Selenium 时,我总是收到“弃用警告”
- arrays - 合并数组值 - vuejs
- sql-server - SSIS OLE DB 源从 Oracle 数据源中随机丢失行
- r - 如何分隔不同列中的多项选择短语(谷歌表单)?
- anylogic - 如何编写一个 for 循环来获取整个表的信息
- ruby - nio4r gem 的问题:安装 nio4r (1.2.1) 时出错,Bundler 无法继续
- python-3.x - 如何将数据框从宽转换为长
- graphql-js - watchQuery 如何与 ApolloClient 配合使用
- git - Jenkins Pipeline 和 SSH 密钥 - Git 代理有效,SSH 代理无效