![](/img/trans.png)
[英]In Typescript how to make a property required if another optional property is set?
[英]How do i make a field in an interface conditionaly optional or required in typescript?
我将 typescript 与 react 一起使用,并且我希望组件仅在该问题是isDraggable
= true 时才需要道具DragActions
。
我试过这样的东西,知道它可能不正确。
type IDragPayload = {
dragHandleProps: any;
};
type TDragActions = {
isDraggable : true, dragActions : IDragPayload
} | {isDraggable : false, dragActions? : never};
interface IQuestionCard
{
isDraggable:boolean;
DragActions : TDragActions;
}
const foo:IQuestionCard = {
isDraggable : false
}
你快到了,只需将parentQuestion
可选:
type TParentQuestion = {
isSubQuestion: true,
parentQuestion: Question
} | { isSubQuestion: false, parentQuestion?: never }
interface Question {
isSubQuestion?: boolean,
parentQuestion: TParentQuestion
}
declare const question: Question;
const foo: TParentQuestion = { //OK
isSubQuestion: false
}
const bar: TParentQuestion = { // OK
isSubQuestion: true,
parentQuestion: question
}
const baz: TParentQuestion = { // KO
isSubQuestion: false,
parentQuestion: question
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.