Home  >  Q&A  >  body text

Is there a way to use ESLint to force destructuring objects to be typed inline, rather than using a separate type definition?

I want to force us to always type destructuring objects inline instead of creating a separate type definition. For example, for React components, I want to force all of our code to use this pattern:

const SomeComponent = ({ foo, bar }: { foo: string, bar: boolean }) => {
  return...
}

instead of:

type Props = {
    foo: string,
    bar: boolean,
};

const SomeComponent = ({ foo, bar }: Props} => {
  return...
}

I checked the ESLint rules and didn't find anything similar. Does anyone have any suggestions?

P粉445714413P粉445714413258 days ago404

reply all(1)I'll reply

  • P粉530519234

    P粉5305192342024-02-27 18:49:03

    As far as I know - there are currently no existing lint rules that enforce this mode.

    You can enforce lint rules using no-restricted-syntax (Example), but as the comments in your post suggest - this Not a good idea.

    It is not possible to create a selector that only matches "reactive function components" because reactive function components are just functions. So (as my example shows) this simple approach will create a lot of noise and false positives in your codebase - which is bad because it creates noise for your team.

    You can create custom rules <来减少误报率, but you can never really make this number zero.


    BTW - this coding style is not good as it goes against industry conventions. It is very common and popular to define a separate type so that it can be imported into a consumer and combined with other types - for example when creating higher-order or wrapper components.

    By always defining the type inline, you make it harder because you have no choice but to get the prop type via Params<typeof MyComponent>[0].

    reply
    0
  • Cancelreply