Bo Chen
Bo Chen

Reputation: 727

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!

Upvotes: 0

Views: 48

Answers (1)

Jared Smith
Jared Smith

Reputation: 21926

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

Upvotes: 1

Related Questions