【问题标题】:Spreading Extended Type Props into Typescript Interface将扩展类型道具传播到 Typescript 接口
【发布时间】:2021-03-07 02:44:17
【问题描述】:

我有以下接口:

interface ButtonProps {
  name: string;
}

interface IconButtonProps {
  name: string;
  icon: string;
}

我正在尝试为以下组件创建类型:

<MyGenericComponent component={button} name="button">...
<MyGenericComponent component={iconButton} name="icon-button" icon="icon">...

我的想法是我无法键入代表 MyGenericComponentProps 的接口,以便它可以接受 component 道具中的反应组件,只要给它的所有其他道具都是给定组件的那些道具会接受!

类似这样的:

interface MyGenericComponentProps<T> extends T {
  component: React.FC<T>;
}

...上面的T 可以是ButtonPropsIconButtonProps。我知道我不能扩展T,因为它是静态未知的,但是我如何确保给出的其余道具是ButtonPropsIconButtonProps 的道具?

更新:这是回答后的组件定义:

import React from 'react';
import { ButtonProps, IconButtonProps } from '@material-ui/core';

type MyGenericComponentProps<T> = {
    component: React.FC<T>;
} & {
    [key in keyof T]: T[key];
};

const MyGenericComponent = <T extends object>({ component, ...props }: MyGenericComponentProps<T>) => {
    // ... more code here
    const Component = component;
    return <Component {...props} />;
};

export default MyGenericComponent;

【问题讨论】:

    标签: typescript typescript-typings typescript-generics


    【解决方案1】:

    如果将使用哪种类型的 TS 实体(类型或接口)没有意义,那么您可以将其键入为类型而不是接口:

    type MyGenericComponentProps<T> = {
      component: React.FC<T>;
    } & {
      [key in keyof T]: T[key];
    }
    

    [更新]:

    你需要修改甚至简化一些片段:

    type MyGenericComponentProps<T> = {
      component: React.FC<T>;
      props: T; 
    }
    
    const MyGenericComponent = <T extends object>({component: Component, props}: MyGenericComponentProps<T>) => {
      // ... more code here
      return <Component {...props}/>;
    };
    

    【讨论】:

    • 谢谢。问题是在尝试实现MyGenericComponent 之后,我收到以下错误:Type 'Pick, Exclude>' is not assignable to type 'IntrinsicAttributes & T & {孩子?:反应节点; }'。类型 ‘Pick, Exclude>’ 不可分配给类型 ‘T’。 'Pick, Exclude>' 可分配给'T' 类型的约束,但'T' 可以用约束'MyGenericComponentProps'.ts(2322) 的不同子类型实例化)
    • 仅供参考,我在MyGenericComponent 中尝试做的是let Component = component 然后&lt;Component {...props} /&gt; ,我得到了上面的错误。
    • 请说明你如何定义MyGenericComponent
    • 我刚刚更新了问题以分享完整的定义。提前致谢。
    • 谢谢,但是这样我就没有props 作为接口属性本身的一部分。我不想在 props 对象中传递道具,而是直接传递。
    【解决方案2】:
    interface ButtonProps {
      name: string;
    }
    
    interface IconButtonProps extends ButtonProps{
      icon?: string;
    }
    

    interface MyGenericComponentProps<IconButtonProps>{
      component: React.FC<IconButtonProps>;
    }
    

    不知道 react,但是使用 typescript 你可以扩展接口并声明可选属性。然后这将接受 ButtonProps 和 IconButtonProps

    【讨论】:

      猜你喜欢
      • 2021-08-07
      • 2015-04-01
      • 2022-12-06
      • 2018-04-09
      • 2018-06-20
      • 1970-01-01
      • 2020-05-04
      • 2018-09-23
      • 2019-05-20
      相关资源
      最近更新 更多