首页 > 解决方案 > 为什么打字稿将联合中的属性标记为不存在?

问题描述

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

但是没有更好的方法吗?

标签: typescriptgraphqlapolloreact-apollo

解决方案


由于联合可能是多种类型之一,因此您应该检查__typename属性以确定使用 switch 或 if 语句使用的类型:

function exampleUsage (query: GetTopicFeedbacksCountQuery) {
  if (query.topic.__typename === 'TopicModelAsEditor') {
    console.log(query.topic.feedbacksCount)
  }
}

推荐阅读