[英]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.