LoginSignup
0
0

More than 1 year has passed since last update.

functionリターンが複数なら、union typeよりgenericを使う。

Posted at

始めに

getDataはreturn typeとして、NewsFeedとNewsDetailを持てるとすると、
function名の後ろにunion typeを使い、【NewsFeed[] | NewsDetail】のようにすれば、二つのtypeに対応できます。
ここで、getData()がreturnするtypeは二つです。Typescript側は、getDataはどのtypeをリターンするの?NewsFeed?NewsDetail?になります。type guardのような状況になっちゃいます。それでtype guardをかけて対応することも可能ですが、
ここでは二つのapiしか対応してないですが、将来に100個のapiを対応するとなったら大変になります。
この場合にgenericを使うことが可能。
type NewsFeed = News & {
  readonly points: number;
  readonly comments_count: number;
  read?: boolean; 
}

type NewsDetail = News & {
  readonly comments: NewsComment[];
}

function getData(url: string): NewsFeed[] | NewsDetail{
    ajax.open('GET', url, false);
    ajax.send();
    return JSON.parse(ajax.response);

const newsContent = getData("https://api.hnpwa.com/v0/news/1.json")
const newsFeed = getData("https://api.hnpwa.com/v0/news/1.json")
}

generic type

getData<T>(url: string): <T> のようにgenericを定義できます。
inputがT typeなので、outputもT typeにするという意味で、
newContent = getData<NewsDetail> となると、<NewsDetail>のNewsDetailをgetData<AjaxResponse>のAjaxResponseが受け取って、そのままreturn typeをNewsDetailにすることになります。
今のケースは、簡単なgenericの使い方で、これ以外にもいろんな使い方があり後でまた整理したい。

type NewsFeed = News & {
  readonly points: number;
  readonly comments_count: number;
  read?: boolean; 
}

type NewsDetail = News & {
  readonly comments: NewsComment[];
}

function getData<AjaxResponse>(url: string): AjaxResponse {
    ajax.open('GET', url, false);
    ajax.send();
    return JSON.parse(ajax.response);
}

const newsContent = getData<NewsDetail>("https://api.hnpwa.com/v0/news/1.json")
const newsFeed = getData<NewsFeed[]>("https://api.hnpwa.com/v0/news/1.json")
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0