React+TS实践技巧

276 阅读1分钟
  1. Service 类型化: 将项目中的请求接口参数和返回值进行类型检查和代码提示,前后端同一接口格式规范,使用Swagger、YAPI、GraphQL自动生成 TypeScript 接口调用代码;

  2. Component 类型化:

    • 类式组件: React.ComponentReact.PureComponent 基类;

    • 函数组件: React.FunctionComponentReact.FC),对于编写函数组件而言,显式注解类型是一个好的实践;

      // 任意组件类型
      type ComponentType<P = {}> = ComponentClass<P> | FunctionComponent<P>;
      // 元素类型 
      React.ElementType
      // 元素节点类型 
      React.ReactElement
      // 节点类型 
      React.ReactNode
      // JSX 元素类型 
      JSX.Element => React.ReactElement<any, any>
      
    • 高阶组件类型

      interface IHOCProps { injectId: number; }
      interface IOwnProps { ownId: number; }
      const hoc = <C extends React.ComponentType<any>>(cp: C) => cp;
      const InjectedCp1 = hoc(OriginalCp as React.ComponentType<IOwnProps>);
      const InjectedCp2 = hoc(OriginalCp as React.ComponentType<Omit<IHOCProps & IOwnProps, 'injectId'>>);
      
    • 路由组件类型: import { RouteComponentProps } from 'react-router-dom';

    • Redux 类型化: Redux 类型化涉及 stateactionreducer 三要素类型化,因为分别类型化三要素的形式写起来十分复杂,所以可以借助 typesafe-actionsredux-actionsrematchdvajs@ekit/model 等工具更清晰、高效地组织 Redux 代码;

      // TS4.1 模板字面量类型
      type PrefixType<P extends string, N extends string> = `${P}/${Capitalize<string & N>}`;
      type UserLoginAction = PrefixType<'User', 'login'>; // 'User/Login'