ジェネリクス

TypeScriptでジェネリクス(Generics)を理解するための簡単なチュートリアル | I am mitsuruog

こちらを参考にジェネリクスを使ったコードを書いてみました。

User クラスと Company クラスを定義して、それらの配列にオブジェクトを追加できるmerge関数を定義します。

class User {
  id!: number;
  firstName!: string;
}

class Company {
  id!: number;
  name!: string;
}

function merge<T extends { id: number }>(array: T[], newValue: T): T[] {
  const index = array.findIndex(item => item.id === newValue.id);
  if (index === -1) {
    return [
      ...array,
      newValue,
    ];
  } else {
    return [
      ...array.slice(0,index),
      newValue,
      ...array.slice(index + 1),
    ];
  }
}

const userArray = [
  { id: 1, firstName: 'Taro' },
  { id: 2, firstName: 'Hanako' },
];

console.log(merge(userArray, { id: 3, firstName: 'Tom' }));
console.log(merge(userArray, { id: 4, firstName: 'Mary' }));

const companyArray = [
  { id: 1, name: 'AAA' },
  { id: 2, name: 'BBB' },
]

console.log(merge(companyArray, { id: 3, name: 'CCC' }));

{ id: number } という制約のある T という型を定義して、merge関数の型定義に使用しました。