Dems314
Dems314

Reputation: 337

How do i make a field in an interface conditionaly optional or required in typescript?

Im using typescript with react and i want a component to require a prop DragActions ONLY if that question is a isDraggable = true.

i tried something like this, knowing it probably isn't right.

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
}

Upvotes: 0

Views: 53

Answers (1)

Matthieu Riegler
Matthieu Riegler

Reputation: 54559

You're almost there, just make parentQuestion optional :

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
}

Playground

Upvotes: 1

Related Questions