Define non-arrow React functional component for TypeScript?

前端 未结 3 1410
面向向阳花
面向向阳花 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:47

    How do you do the same for a non-arrow function?

    import * as React from 'react';
    
    function NonFatArrow(): React.ReactElement {
        return (
          <>
            Non-fat-arrow function
          
        );
    }
    
    const FatArrow: React.FunctionComponent = _props => {
      return (
        
    ); };

    Is there any practice difference?

    Stepping aside from React and Typescript, in ES6 a fat arrow function captures few things including this and will carry the capture along self. So if there are thousands of such functions then there will be overhead of captures.

    Coming back to React and Typescript, this is not used in React.FunctionComponent(s) however if Typescript transpiler of your choosing transpiles to ES6 then there will be fat arrow functions with captures.

    So it all depends on the chosen transpiler and its settings. With Typescript compiler, if you have "target": "es5" in tsconfig.json, then the FatArrow component will be transpiled into ES5 function. Changing the setting to "target": "es6" ensures FatArrow is transpiled to an arrow function. With Babel as transpiler your mileage may vary.

提交回复
热议问题