DEV Community

Discussion on: How would you name the TS interface like this(TS types naming convention)?

Collapse
 
bias profile image
Tobias Nickel

I have an other thought on the topic, And I think this is an approach that is promoted/adopted by the golang community(correct me if i am wrong).

What about having only one global (maybe in a types directory) user type/interface and other versions with only partial set of fields, they are only defined local in the module that uses them.

Collapse
 
mrdulin profile image
official_dulin • Edited

I have this thought as well. Ideally, we should have interfaces corresponding to the data model represented by the database tables, and I remember that there are ORM and Code Generation tools that can do this.

In addition, for the front end, we should define the types and interfaces for the view model.

The model(type, interface) conversion process is as follows:

API => Frontend representation: Domain Model Interface => View model interface
Frontend representation => API: View model interface => Domain Model interface.

We will convert the domain model interface that contain all fields to target types through TS's Utility Types or Map Type rather than repeated definitions.

The naming convention for the derived types just like my above comment. The key point of the naming convention should be readability, scalability, reusability and maintainability.

More naming convention examples:

type UserEntity {
  id: string;
  name: string;
  role: string;
  email: string;
}
// Comsumer side
// For react hook
type UseGetUserQueryPayload = {
  id: Pick<UserEntity, 'id'>
}
const useGetUserQuery = (payload: UseGetUserQueryPayload) => {}

// For API service methods
type GetUsersResult = Pick<UserEntity, 'id' | 'name'>;
const getUsers = (): Promise<GetUsersResult> => fetch(/.../)

// But what name should be use for below situation
type UserOfProduct = Pick<UserEntity, 'id' | 'name'>;
type Product = {
  id: string;
  name: string;
  // I think it's not prefect. 
  // UserOfProduct is same with GetUsersResult, duplicated!
  user: UserOfProduct;   
}
Enter fullscreen mode Exit fullscreen mode