Let’s assume that we have several types:
interface ModalType {
preview: ReactElement;
edit: ReactElement;
}
interface PreviewModalProps {
username: string;
}
interface EditModalProps {
title: string;
description: string;
}
type ModalPropsType = PreviewModalProps | EditModalProps;
const modals: ModalType = {
preview: <PreviewModalComponent />
edit: <EditModalComponent />
}
type ModalName = keyof ModalType;
const modalName: ModalName = 'preview'
// pass it somewhere else
In this example I want to be sure, that if our modalName
has the preview
value,then our props should correspond to a PreviewModalProps
, not the EditModalProps
.
How can I connect it everything toghether?
2
Answers
If you want to combine ModalProps,
Combining with "&" operator, you can achieve it.
There’s no way to do that at the top level, but you can easily do that by creating a couple of wrappers to form a discriminated union:
If you use those interfaces the compiler won’t let you assign the wrong ones, and if you check the discriminant (name in this case) in a conditional the compiler will narrow the type: