DEV Community

Discussion on: React TS: Don't repeat the type when you pass functions as props, use their types.

Collapse
 
mrispoli24 profile image
Mike Rispoli

So I actually used to do this but now heir on the side of repeating myself and encourage the team to do the same here. One of the things that can start to happen to large typescript code bases like this is you can end up coupling lots of components together by way of their type.

By repeating the type, you may be violating DRY but you avoid making these two components dependent upon one another. It's definitely a delicate balance though.

Collapse
 
lico profile image
SeongKuk Han • Edited

Yes, you're right. I agree with you. thanks for the comment :). Let's say, you make a component and use a type of another component in the component like that, they must be dependent. When the one changes, another one would be affected. If you aren't considered it, that would be not good in a way. But in the examples, I think that is totally fine. That component already depends on the SignUpForm Component. And used the field type.

Collapse
 
frontendtony profile image
Anthony Oyathelemhi

Or, avoid both issues altogether and define the type in a separate file and import in both components

Collapse
 
mrispoli24 profile image
Mike Rispoli

I think you end up in the same place where a bunch of components end up dependent on the same type. I do like the idea of using Omit and Partial to extend a single use case for different areas, but tread carefully with the coupling still.

Thread Thread
 
mrwensveen profile image
Matthijs Wensveen

Defining the type in a separate file is a good idea when it makes sense in your domain. In this case a Credentials type would be a good idea. If the type only matters in a specific component you'll want to avoid tight coupling, so I wouldn't export the SignupFormProps or even the onSubmit handler type.

const handleSubmit = (values: Credentials) => {
  console.log(values);
};
Enter fullscreen mode Exit fullscreen mode

Looks okay to me.

Collapse
 
torver213 profile image
Peter Kelvin Torver

Nice one. I always go with this. Don't see the reason why people are making a big deal out of this. Keeping types in a separate file and importing them where necessary makes your application obeys DRY principle.

Collapse
 
duysolo profile image
Justin Phan

Yes I agree with that. Why don't we declare the type in a new file instead?

Collapse
 
lico profile image
SeongKuk Han • Edited

Yes, that's a good idea. Thanks for your opinion :) Defining types in a seperate file and components that need the types import them.

But if you care every types like even a type of one of props, you might end up need a lot of types.

And other packages that you use might not have all types you need.