Ahmed Samy
Ahmed Samy

Reputation: 1046

How to declare one of a class properties to be compulsory if the other is entered in Typescript?

In the following example, I want the user of the class to be able to use it without having to enter a message unless visible is set to true.

type ClassProps = {
  visible: boolean;
  message: string;   // message should be compulsory if visible
}

Upvotes: 0

Views: 24

Answers (1)

jcalz
jcalz

Reputation: 328097

You really want to build this up as a union of two object types: one where visible is false and message is optional, and the other where visible is true and message is required:

type ClassProps = { visible: false; message?: string; } | { visible: true; message: string }

This, I think, behaves as you desire:

const ok1: ClassProps = { visible: false }; // okay
const ok2: ClassProps = { visible: false, message: "invisible" }; // okay
const ok3: ClassProps = { visible: true, message: "visible" }; // okay
const bad: ClassProps = { visible: true }; // error!
//    ~~~ <---
// Property 'message' is missing in type '{ visible: true; }'
// but required in type '{ visible: true; message: string; }'

Okay, hope that helps; good luck!

Link to code

Upvotes: 1

Related Questions