DEV Community 👩‍💻👨‍💻

official_dulin
official_dulin

Posted on

Pick and large interface V.S. small interface. Which one is better?

When I use the option 1 to make my business types(T0, T1, etc...), I found I repeated Pick<ChannelBaseInfo1, 'channelCode'> too many. So maybe option 2 is better? Please give me some suggestion. Thanks.

// Option 1. 
type ChannelBaseInfo1 = {
  channelCode: string;
  channelName: string;
}

// Use Pick utility type
type T0 = Pick<ChannelBaseInfo1, 'channelCode'> & {
  t0: string;
}

type T1 = ChannelBaseInfo1 & {
  t50: string;
}

type T2 = Partial<Pick<ChannelBaseInfo1, 'channelCode'>> & {
  t2: any;
}

// a lots of types using ChannelBaseInfo1 or Pick<ChannelBaseInfo1, 'channelCode'>
// ...
type T100 = Pick<ChannelBaseInfo1, 'channelName'> & {
  t100: string;
}

// Option 2.
type ChannelCode = {
  channelCode: string;
}
type ChannelName = {
  channelName: string;
}
type ChannelBaseInfo2 = ChannelCode & ChannelName;

type T101 = ChannelCode & {
  t101: string;
}

type T102 = ChannelBaseInfo2 & {
  t102: string;
}
type T103 = Partial<ChannelCode> & {
  t103: string;
}
// a lots of types using ChannelBaseInfo2, ChannelCode and ChannelName
// ...
type T200 = ChannelName & {
  t200: string;
}
Enter fullscreen mode Exit fullscreen mode

TypeScript Playground

Top comments (2)

Collapse
 
bias profile image
Tobias Nickel

small interfaces.
and the ChallelBaseInfo should be named ChannelInfo and the properties should be named code and number, otherwise you create a lot of stutter. it might help if you try reading your code out loud 😉

Collapse
 
mrdulin profile image
official_dulin • Edited on

Yeah. I understand I don't need to add channel prefix to each property like channelXXX pattern because we already have the ChannelInfo context. That's not the point. This is just a demo.

Small interfaces like this:

type ChannelCode = {
   code: string;
}
type ChannelName = {
   name: string;
}
type ChannelInfo = ChannelCode & ChannelName;
Enter fullscreen mode Exit fullscreen mode

Actually, this will raise another question. How to name the types. If the code property is a union type rather than string. How should we name the ChannelCode object type?

type ChannelCode = '0' | '1' | '2';
type ChannelCodeDTO = {
   code: ChannelCode;
};
Enter fullscreen mode Exit fullscreen mode

In order to distinct the ChannelCode union type and object type names, I add a suffix like DTO. There are some choices:

ChannelCodeObject  
ChannelCodeStruct 
ChannelCodeDTO
Enter fullscreen mode Exit fullscreen mode

Or,

type ChannelCode = {
   code: '0' | '1' | '2';
};
// later
type Biz = {
  channelCode: ChannelCode['code'];
}
Enter fullscreen mode Exit fullscreen mode

How will you handle this situation?

The Complete Guide to Full Stack Web3 Development

>> Check out this classic DEV post <<