[英]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. 我正在尝试将此定义转换为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.
表示如果类型等于“ stay”,则Stay成员必须包含IStay实现。 And otherwise, stay can be empty.
否则,留空即可。
How can I define that as an interface in TypeScript? 如何在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> </> );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.