Javascript 在TypeScript接口中定义requiredIf成员

Javascript 在TypeScript接口中定义requiredIf成员,javascript,typescript,react-proptypes,Javascript,Typescript,React Proptypes,我有以下道具类型定义: const calendarEventPropType = PropTypes.shape({ id: PropTypes.string.isRequired, startDate: PropTypes.instanceOf(Date).isRequired, endDate: PropTypes.instanceOf(Date).isRequired, title: PropTypes.string.isRequired, typ

我有以下道具类型定义:

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'),
});
我正在尝试将此定义转换为TypeScript。我作了以下发言:

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

export interface ICalendarEvent extends ICalendarLayer {
    title: string;
    type: string;
    stay?: IStay;
}
但我想说得更具体一些。意味着若类型等于“stay”,则stay成员必须包含IStay实现。否则,停留时间可能为空。
如何在TypeScript中将其定义为接口?

使用联合类型:

 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 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;
接口ICalendarLayer{
id:编号;
起始日期:日期;
结束日期:日期;
}
导出接口ICalendarEvent扩展ICalendarLayer{
标题:字符串;
类型:字符串;
停留?:布尔值;
}
功能儿童测试(道具:ICalendarEvent){
const{endDate,id,startDate,stay,title,type}=props;
return();
}
函数ParentTest(参数:any){
const[stay,setStay]=useState(false)
const actionStay=()=>{
/*如果保持控制*/
固定(!停留);
}
返回(
);
界面ICalendarLayer{
id:编号;
起始日期:日期;
结束日期:日期;
}
导出接口ICalendarEvent扩展ICalendarLayer{
标题:字符串;
类型:字符串;
停留?:布尔值;
}
功能儿童测试(道具:ICalendarEvent){
const{endDate,id,startDate,stay,title,type}=props;
return();
}
函数ParentTest(参数:any){
const[stay,setStay]=useState(false)
const actionStay=()=>{
/*如果保持控制*/
固定(!停留);
}
返回(
);

ICalendarEvent可以是一个接口吗?为什么要这样?您可以通过组合更多接口来轻松扩展它。您使用了|。您的解决方案不会强制我使用标题。标题是必需的(我不想在ICalendarEvent中提到的每个接口中都设置它。它是。两个接口都扩展了
IRegularEvent
。ICalendarEvent可以是一个接口吗?为什么要这样?你可以通过组合更多接口来轻松地扩展它。你使用了|。你的解决方案不会强迫我使用标题。标题是强制性的(我不想在ICalendarEvent中提到的每个接口中都设置它。它设置了。两个接口都扩展了
IRegularEvent
)。