简体   繁体   中英

Define requiredIf member in TypeScript interface

I have the following prop type definition:

const calendarEventPropType = PropTypes.shape({
    id: PropTypes.string.isRequired,
    startDate: PropTypes.instanceOf(Date).isRequired,
    endDate: PropTypes.instanceOf(Date).isRequired,
    title: PropTypes.string.isRequired,
    type: PropTypes.oneOf(['stay']).isRequired,
    stay: requiredIf(stayPropType, props => props.type === 'stay'),
});

I am trying to convert this definition into TypeScript. I made the following:

interface ICalendarLayer {
    id: Number;
    startDate: Date;
    endDate: Date;
}

export interface ICalendarEvent extends ICalendarLayer {
    title: string;
    type: string;
    stay?: IStay;
}

But I want to be more specific. Means that if type equals "stay", stay member must contain IStay implementation. And otherwise, stay can be empty.
How can I define that as an interface in TypeScript?

Use a Union type:

 interface IRegularEvent extends ICalendarLayer {
   title: string;
   type: "someother" | "type";
   // stay?: IStay; // not sure if you need that?
 }

 interface IStayEvent extends ICalendarLayer {
   type: "stay";
   stay: IStay;
 }

 export type ICalendarEvent = IRegularEvent | IStayEvent;
interface ICalendarLayer { id: Number; startDate: Date; endDate: Date; } export interface ICalendarEvent extends ICalendarLayer { title: string; type: string; stay?: boolean; } function ChildTest(props: ICalendarEvent) { const {endDate,id,startDate,stay,title,type} = props; return(<></>); } function ParentTest(params:any) { const [stay, setStay] = useState(false) const actionStay = () => { /* if stay control */ setStay(!stay); } return( <> <ChildTest endDate={new Date()} startDate={new Date()} id={1} stay={stay} title="lorem" type="lorem" /> <button onClick={actionStay}></button> </> );

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