在严格模式下使用 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)
}
}
关于typescript - 为什么 typescript 将联合中的属性标记为不存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59104086/