Define non-arrow React functional component for TypeScript?

前端 未结 3 1448
面向向阳花
面向向阳花 2021-01-17 23:32

You can define a React functional component\'s types in TypeScript with this:

export const Component: React.FC = () => {
  return // Stuff
};
         


        
3条回答
  •  青春惊慌失措
    2021-01-17 23:55

    There is better type support for some certain cases when you declare component with const. To understand these cases you can have a look at the React.FC type:

    type FC

    = FunctionComponent

    ; interface FunctionComponent

    { (props: PropsWithChildren

    , context?: any): ReactElement | null; propTypes?: WeakValidationMap

    ; contextTypes?: ValidationMap; defaultProps?: Partial

    ; displayName?: string; }

    Since react component (even function component) is a bit more than just a plain function - specifying precise type for component itself gives you better type inference:

    
    function FooAsFunc({ children }) { // children has 'any' type
      return 1234
    }
    
    const FooAsConst: React.FC = ({ children }) => {
      return 1234 // type error: typescript knows that 1234 is not valid react component return type
    }
    
    FooAsFunc.displayName = new Date()
    FooAsConst.displayName = new Date() // type error: 'displayName' suppose to be of a type string
    

    In the end, same type safety can be achieved with function declaration as well, but it just requires more code.

提交回复
热议问题