BuoySoftware / guides

Documentation for Buoy Software
2 stars 0 forks source link

Use `unknown` PropType for Components with no Props #52

Closed aq1018 closed 1 year ago

aq1018 commented 1 year ago

Example:

export const ComponentWithNoProps: React.FC<unknown> = () => {
  // render some stuff here
};

Notice the use of unknown type in FC generic parameter.

This gives better type information about the props type when using this component. It informs us that this component doesn’t accept any props. Otherwise, by default the props will be of type any, which we should do our best to avoid.

acostanzo commented 1 year ago

I don't think we should pass unknown here. It feels misleading as the default of the optional generic is {}. This means the default type of props is {} opposed to any. If you don't pass anything when rendering a functional component, its first argument still exists and is just an object.

export const ComponentWithNoProps: React.FC = (props) => {
  console.log("props: ", props)
};

----
console output would be something like:
# props: {}

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts#L518

aq1018 commented 1 year ago

@acostanzo

Hmmm... my editor says it any... strange...

I think {} is actually equivalent to any. (See: https://typescript-eslint.io/rules/no-empty-interface/)

An empty interface in TypeScript does very little: any non-nullable value is assignable to {}. Using an empty interface is often a sign of programmer error, such as misunderstanding the concept of {} or forgetting to fill in fields.

I'm not tied down to use unknown though, because unknown doesn't really make that much of a difference. I think maybe we should just close this issue as not changing the default type is probably the way to go.

acostanzo commented 1 year ago

Interesting... I wonder why it says any 🤔 what version of @types/react is present in the repo where you're seeing this?

any and {} are not quite equivalent. And based on the error output below I feel the message provided by {} and Object are a little more meaningful especially since the argument will exist whether you pass props or not.

Screenshot 2022-12-19 at 12 02 31 PM
aq1018 commented 1 year ago

@acostanzo I didn't know they have this much difference, learned something new today. As long as it errors out I'm fine with it. Closing the story.