DEV Community

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

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.