LoginSignup
1

More than 1 year has passed since last update.

【TypeScript】ジェネリクス

Posted at

ジェネリクスとは??

ジェネリクスとは、プログラミング言語の機能・仕様の一つで、同じプログラムコードで様々なデータ型のデータを処理できるようにするもの。
参考:https://e-words.jp/w/%E3%82%B8%E3%82%A7%E3%83%8D%E3%83%AA%E3%82%AF%E3%82%B9.html

同じ処理ばっかなのに引数の型が違うだけで何回も書くのめんどくさくね?というのを解消してくれます。

ジェネリクスを使わない場合

const Example = () => {
  const fillStrArray = (value: string, times: number): string[] => {
    let strArray = new Array(times);
    //与えられたvalueで配列を埋める
    strArray.fill(value);
    return strArray;
  };
  const fillNumArray = (value: number, times: number): number[] => {
    let numArray = new Array(times);
    //与えられたvalueで配列を埋める
    numArray.fill(value);
    return numArray;
  };

  console.log(fillStrArray("hello", 5)); //['hello', 'hello', 'hello', 'hello', 'hello']
  console.log(fillNumArray(10, 5)); //[10, 10, 10, 10, 10]
};

fillStrArrayfillNumArrayはほぼ同じ処理をしているのに2つも書いてしまっています。今は2つの処理だけなので見やすいですが、数が増えていくとどんどん見にくくなってしまいます。

どこが異なっているのかを確認すると

const fillStrArray = (value: string, times: number): string[] => {
const fillNumArray = (value: number, times: number): number[] => {

ここの引数がstringnumberで違うことが分かります。
このような状況の時にジェネリクスが役に立ちます。

ジェネリクスを使った場合

  const fillArray = <T>(value: T, times: number): T[] => {
    let newArray = new Array(times);
    newArray.fill(value);
    return newArray;
  };

  console.log(fillArray<number>(10, 5));//[10, 10, 10, 10, 10]
  console.log(fillArray<string>("good", 5));//['good', 'good', 'good', 'good', 'good']
  console.log(fillArray<boolean>(true, 5));//[true, true, true, true, true]
  console.log(fillArray<"hello">("hello", 5));//['hello', 'hello', 'hello', 'hello', 'hello']

ジェネリクスを使った場合では引数の型指定のところを<T>とします

const fillArray = <T>(value: T, times: number): T[] => {

こうすることによりnumberstringを型指定した処理をたくさん書かなくても済むようになりました。

例えば、fillArray<string>とすれば、Tが指定されている<T>T[]<string>string[]に変化します。

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
1