简体   繁体   中英

type constraints in Generic types

I have below code

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;

where I want to assign dynamicModal to a Component that has props extended from BaseModalProps . the AddToListModal is a good example. If you assign a non-complying component to dynamicModal I want a type error

I've tried a couple of solution and non of them works,,, any ideas? thanks!

You need to make generic type:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM