【问题标题】:type constraints in Generic types泛型类型中的类型约束
【发布时间】:2022-10-06 21:55:02
【问题描述】:

我有以下代码

interface BaseModalProps {
  name:string
}
interface AddToListModalProps extends BaseModalProps {
  name: string;
  age: number;
};
export const AddToListModal: FC<AddToListModalProps> = ({
  name,
  age,
}: AddToListModalProps) => <h1>{`${name} ${age.toString()}`}</h1>;


// bad TS syntax, what is the correct syntax? 
export const dynamicModal: FC<{T extends BaseModalProps}> = AddToListModal;

我想将dynamicModal 分配给具有从BaseModalProps 扩展的道具的组件。 AddToListModal 就是一个很好的例子。如果您将不符合要求的组件分配给 dynamicModal 我想要一个类型错误

我已经尝试了几个解决方案,但没有一个有效,,,有什么想法吗?谢谢!

    标签: reactjs typescript


    【解决方案1】:

    您需要制作泛型类型:

    export type DynamicModal<T extends BaseModalProps> = FC<T>;
    
    // Works fine
    export const AddToListModal: DynamicModal<AddToListModalProps> = ({
      name,
      age,
    }) => <h1>{`${name} ${age.toString()}`}</h1>;
    
    // Errors as expected
    export const EpicFail: DynamicModal<{ a: number }> = ({ a }) => <p>{a.toString()}</p>;
    

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多