How to make a dependent types in Typescript

How to make a dependent types in Typescript


Suppose you have a contact info type containing email and phone number in which one of them is mandatory but not both.

How are we going to tell Typescript that if email is defined, then phone number is optional or if phone number is defined then email is optional?

You may be attempting to make both of them optional as the following:

export type ContactInfo = {
  email?: string;
  phoneNumber?: string;
}
Enter fullscreen mode

Exit fullscreen mode

But with that approach, none of the email or phoneNumber property is required and the following syntax is valid:

// valid
const johnDoeContact: ContactInfo = {};
Enter fullscreen mode

Exit fullscreen mode



The solution

We can use Typescript Discriminated Unions to solve it:

export type ContactInfoRequiredEmail = {
  email: string;
  phoneNumber?: string;
};

export type ContactInfoRequiredPhoneNumber = {
  email?: string;
  phoneNumber: string;
};

export type ContactInfo =
  | ContactInfoRequiredEmail
  | ContactInfoRequiredPhoneNumber;
Enter fullscreen mode

Exit fullscreen mode

Now Typescript will throw error with the previous example of John Doe contact but will accept the following example:

// not valid
const johnDoeContact: ContactInfo = {};

// valid
const janeContact: ContactInfo = {
  email: 'janecontact@domain.com',
};

// also valid
const jamesContact: ContactInfo = {
  phoneNumber: '+261343790400',
};
Enter fullscreen mode

Exit fullscreen mode



Source link
lol

By stp2y

Leave a Reply

Your email address will not be published. Required fields are marked *

No widgets found. Go to Widget page and add the widget in Offcanvas Sidebar Widget Area.