Skip to content

Latest commit

 

History

History
68 lines (51 loc) · 3.69 KB

File metadata and controls

68 lines (51 loc) · 3.69 KB

Item 39: Prefer Unifying Types to Modeling Differences

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