繁体   English   中英

如何在 typescript 中有条件地使接口中的字段成为可选或必需?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM