typescript - 为什么打字稿将联合中的属性标记为不存在?
问题描述
在严格模式下使用 TS 3.7.2,我从 graphql-codegen 生成了这种类型:
type GetTopicFeedbacksCountQuery = { __typename?: 'Query' } & {
topic: Maybe<
| ({ __typename?: 'TopicModelAsMember' } & Pick<TopicModelAsMember, 'id'>)
| ({ __typename?: 'TopicModelAsEditor' } & Pick<
TopicModelAsEditor,
'generateToken' | 'id'
> & { feedbacksCount: TopicModelAsEditor['enrolmentsCount'] })
>
}
每当我尝试使用它并且我想访问feedbacksCount
属性时,我都会收到这种类型的错误:
现在我知道我可以强制 TS 使用这样的类型以避免类型错误:
const feedbacksCount = (topic as TopicModelAsEditor & {
feedbacksCount: TopicModelAsEditor['enrolmentsCount']
}).feedbacksCount
但是没有更好的方法吗?
解决方案
由于联合可能是多种类型之一,因此您应该检查__typename
属性以确定使用 switch 或 if 语句使用的类型:
function exampleUsage (query: GetTopicFeedbacksCountQuery) {
if (query.topic.__typename === 'TopicModelAsEditor') {
console.log(query.topic.feedbacksCount)
}
}
推荐阅读
- c# - 时间:2019-06-10 标签:c#drawing,circleguesoutform
- angular - 使用 Promise 时如何进行条件检查并返回自定义对象?
- holochain - holochain 应用程序中文件“holoclient.js”和“holoclient.map”的来源?
- java - 在实体中循环休眠
- code-signing - OSX 网守不拒绝第三方应用程序
- android - 适用于 Android 的 C++ 堆分析器
- ios - 以下二进制文件在迁移到 Swift 4 时使用了不兼容的 Swift 版本
- sqlite - SQlite 中的 PRAGMA Key='SomeKey' 是否加密/解密数据库的整个数据?
- java - 如何将 Java 时区数据库更新到最新版本?
- string - 当硬件不支持 64 位数字时,是否可以将 64 位数字表示为字符串?