属性在类型“对象”上不存在-联合类型

时间:2020-02-29 21:11:49

标签: reactjs typescript

我定义了两个接口:

interface movieProps {
  adult: boolean,
  backdrop_path: string,
  genre_ids: number[],
  id: number,
  original_language: string,
  original_title: string,
  overview: string,
  popularity: number,
  poster_path: string,
  release_date: string,
  title: string,
  video: boolean,
  vote_average: number,
  vote_count: number,
  mediaType: string,
  documentID: string
}

interface gameReleaseDate {
  id: number,
  category: number,
  created_at: number,
  date: number,
  game: game,
  human: string,
  m: number,
  platform: number,
  region: number,
  updated_at: number,
  y: number,
  documentID: string,
  mediaType: string
}

我已使用allCountdownItems: movieProps[] | gameReleaseDate[]定义了具有联合类型的变量,其中包含两种类型的对象。

我正在使用.map()呈现每个项目的信息。我通过使用以下方法来做到这一点:

return (
  <div>
    {(this.state.allCountdownItems as Array<movieProps | gameReleaseDate>).map(item => {
      return (
        <h2>{item.mediaType === "movie" ? item.title : item.game.name}</h2>
      )
    })}
  </div>
)

这给我以下错误:

类型'movieProps |中不存在属性'title'| gameReleaseDate'。 属性“ title”在“ gameReleaseDate”类型上不存在。ts(2339)

如何在不将item声明为any类型的情况下解决此问题?

1 个答案:

答案 0 :(得分:0)

您正试图区分与item.mediaType === "movie"的联合

要使其正常工作,您需要在工会成员上声明文字成员,即

interface movieProps {
  adult: boolean,
  backdrop_path: string,
  genre_ids: number[],
  id: number,
  original_language: string,
  original_title: string,
  overview: string,
  popularity: number,
  poster_path: string,
  release_date: string,
  title: string,
  video: boolean,
  vote_average: number,
  vote_count: number,
  mediaType:'movie' // HERE
  documentID: string
}

interface gameReleaseDate {
  id: number,
  category: number,
  created_at: number,
  date: number,
  game: game,
  human: string,
  m: number,
  platform: number,
  region: number,
  updated_at: number,
  y: number,
  documentID: string,
  mediaType:'game' // HERE
}

更多

Discriminated unions TypeScript