Item 39: Prefer Unifying Types to Modeling Differences

May 10, 2024 ยท View on GitHub

Things to Remember

  • Having distinct variants of the same type creates cognitive overhead and requires lots of conversion code.
  • Rather than modeling slight variations on a type in your code, try to eliminate the variation so that you can unify to a single type.
  • Unifying types may require some adjustments to runtime code.
  • If the types aren't in your control, you may need to model the variations.
  • Don't unify types that aren't representing the same thing.

////## Code Samples

interface StudentTable {
  first_name: string;
  last_name: string;
  birth_date: string;
}

๐Ÿ’ป playground


interface Student {
  firstName: string;
  lastName: string;
  birthDate: string;
}

๐Ÿ’ป playground


type Student = ObjectToCamel<StudentTable>;
//   ^? type Student = {
//        firstName: string;
//        lastName: string;
//        birthDate: string;
//      }

๐Ÿ’ป playground


async function writeStudentToDb(student: Student) {
  await writeRowToDb(db, 'students', student);
  //                                 ~~~~~~~
  // Type 'Student' is not assignable to parameter of type 'StudentTable'.
}

๐Ÿ’ป playground


async function writeStudentToDb(student: Student) {
  await writeRowToDb(db, 'students', objectToSnake(student));  // ok
}

๐Ÿ’ป playground