labs42io / clean-code-typescript

Clean Code concepts adapted for TypeScript
https://labs42io.github.io/clean-code-typescript
MIT License
9.25k stars 1.13k forks source link

Prefer to use base types in some cases #51

Closed matvaleriano closed 2 years ago

matvaleriano commented 2 years ago

I saw in many interviews people that doesn't know that we can access Type['attribute'] like this. In some cases it's good because typescript will show you where code will break. For example

given we have a type Person

type Person = {
  id: string;
  name: string;
}

many people create specific functions like this

const getPersonName = (id: string) => {}

besides if you change the attribute's type or name it'll not break anything and you'll suffer to find every place to update, but when we use like this below

const getPersonName = (id: Person['id']) => {}

typescript will tell you where code will break.

There's another cases for whose use the entire type for function parameter instead of use Pick/Omit/etc.

dimadeveatii commented 2 years ago

@matvaleriano while your point is a valid improvement and a Typescript syntactic sugar to reference field types, it is not necessarily a clean code improvement.

From the perspective of maintaining the code clean and readable, both examples are good. While using id: Person['id'] has some advantages when doing refactorings, the id: string wouldn't compile as well if you change the type.