为什么打字稿将联合中的 属性 标记为不存在?

Why does typescript mark the property in a union as non existent?

在严格模式下使用 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)
  }
}