[英]type constraints in Generic types
我有以下代码
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
我想要一个类型错误
我已经尝试了几个解决方案,但没有一个有效,有什么想法吗? 谢谢!
您需要制作通用类型:
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>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.