【问题标题】:Using Typescript generics for React Functional Components with eslint props validation将 Typescript 泛型用于带有 eslint 道具验证的 React 功能组件
【发布时间】:2020-09-09 01:49:46
【问题描述】:

我想用Typescript在React中创建一个功能组件,我已经按照this Q&A设置好了:

export interface CustomProps<T extends object> extends SomeOtherProps<T> {
  customProp?: number;
}

const CustomComponent: <T extends object>(props: CustomProps<T>) => JSX.Element = {
  customProp = 10,
  ...props
}) => {
  // etc
};

但是,这在eslint 中给了我一个错误,说道具未经验证:

道具验证中缺少'customProp'

我可以尝试通过在默认道具后添加CustomProps 来使用泛型添加道具验证:

export interface CustomProps<T extends object> extends SomeOtherProps<T> {
  customProp?: number;
}

const CustomComponent: <T extends object>(props: CustomProps<T>) => JSX.Element = {
  customProp = 10,
  ...props
}: CustomProps<any>) => {
  // etc
};

但这给了我一个“没有明确的any”的警告。如果我插入T,它就不会知道。那么我该如何解决呢?

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    解决方案在于再次实例化类型,就像为组件声明本身实例化它一样:

    export interface CustomProps<T extends object> extends SomeOtherProps<T> {
      customProp?: number;
    }
    
    const CustomComponent: <T extends object>(props: CustomProps<T>) => JSX.Element = <T extends object>({
      customProp = 10,
      ...props
    }: CustomProps<T>) => {
      // etc
    });
    

    这样,所有的道具都会被正确地验证。

    【讨论】: