Is it possible to restrict optionality in Typescript interfaces based on a boolean value?

Currently, I am working on an interface where I need to implement the following structure:

export interface Passenger {
       id: number,
       name: string,
       checkedIn: boolean,
       checkedInDate?: Date // <- Is it possible to make this field optional only when checkedIn is set to false?
}

Answer №1

Declaring this directly within an interface is not possible. Nevertheless, the desired behavior can be achieved by implementing it in a class:

class Traveler {
   id: number;
   name: string;
   checkInDate?: Date;

   get isCheckedIn() {
      return this.checkInDate != null;
  }       
 }

Answer №2

Is it possible for you to simply disregard the value stored in the variable checkedInDate when the status of checkedIn is marked as true? Perhaps you could consider implementing a solution similar to the following:

if(!pessageobj.checkedIn) {
 pessageobj.checkedInDate = new Date();
} else {
pessageobj.checkedInDate =  set to a default date such as minimum date;
}

Answer №3

Understanding Union Types:

export type Traveler = {
    id: number,
    name: string,
    checkedIn: true,
    checkedInDate: Date
} | {
    id: number,
    name: string,
    checkedIn: false,
    checkedInDate?: Date // optional field
}

Answer №4

A parameter template can provide a more specific type for checkedIn rather than just boolean. This allows an intersection to include either the optional or mandatory version of checkedInDate.

export type Passenger<A extends boolean> = {
    id: number;
    name: string;
    checkedIn: A;
} & (A extends false
    ? {
        checkedInDate?: Date;
    }
    : {
        checkedInDate: Date;
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

substitute elements within an array using elements from a different array

Looking to swap object(s) in an array with another array while maintaining the original order. Here is arrayOne: [ { "color": "#f8edd1", "selected": true }, { "color": "#d88a ...

Prisma unexpectedly updates the main SQL Server database instead of the specified database in the connection string

I have recently transitioned from using SQLite to SQL Server in the t3 stack with Prisma. Despite having my models defined and setting up the database connection string, I am encountering an issue when trying to run migrations. Upon running the commands: ...

Is it possible to create Android apps using HTML and JavaScript?

I have a strong foundation in HTML, Javascript, CSS, and AJAX, but I want to venture into Android application development. However, I lack knowledge of Java technology. Is it feasible to develop Android apps using HTML or JS? If anyone has experience wit ...

HTML dropdown menu to trigger an action with the submitted URL

I need assistance creating a menu of options with corresponding URL actions. Here is the structure I have in mind: <form> <select> <option value="1">1</option> <option value="2">2</option> <option value="3 ...

Vue Deep Watcher fails to activate when the data is altered

While the countdown timer is functioning properly, it seems that the deep watcher is not working as expected. Despite attempting to log the new value of seconds in the console, it does not display anything even though the countdown timer continues to funct ...

How do I ensure that in Vue.js, the select element always has the first option selected even when other options are dynamically shown or hidden?

In my Vue app, I have a select element that dynamically shows or hides options based on the user's previous selections. For example: <select id='animal' v-model='values.animal.selected'> <option value='cat' ...

The JavaScript calculator fails to display the value of buttons on the screen when they are pressed

I was attempting to create a calculator using JavaScript, but when I click on any button, nothing happens (the buttons don't display their values on the calculator's screen). My text editor (vs code) didn't indicate any errors, but upon insp ...

utilizing services across multiple controller files

Service - optionService.js controllers - app.js & welcomeCtrl.js & otherCtrl.js app.js var app = angular.module('mainapp', ['mainapp.welcome','optionServiceModule']); app.controller('mainappCtrl', functio ...

Unable to process login information with form method post on basic login page

Hi, I've been struggling with a simple login page issue. It works fine with Bootstrap, but I want to switch to Angular Material Design. I've been searching for the problem for about 3-4 hours and can't find anything. I suspect that the form ...

Effortless navigation with smooth scrolling on anchor links in react/next.js

Can smooth scrolling be achieved using only CSS when clicking on an anchor link within a react component? ... render( <a href="#smooth-link">Link To There</a> .... <div id="smooth-link"> .... ...

Have I repeated myself in defining my class properties?

Currently, I'm enhancing my understanding of Typescript with the development of a discord.js bot. However, I have come across a piece of code and I am uncertain about its redundancy: import Discord from 'discord.js'; export default class B ...

Looking to dynamically track an event in Firestore?

Is it possible to implement a method in Node.js that allows me to listen for changes on a node, similar to the following path? organizations/{org_slug}/projects/{pro_slug}/calculations/{calc_slug} I have successfully done this in a Firebase Cloud Functio ...

Is it necessary to specify a data type for the response when making an AJAX POST request?

After carefully reviewing my code, I have ensured that all the variables in my JavaScript match and are properly set up. Additionally, I have confirmed that all the variables in my data array for my AJAX request correspond correctly to my $_POST['var& ...

Retrieve information using AJAX via POST method

I find myself in a bit of a pickle at the moment. I've been researching for hours, and I still can't seem to figure out this seemingly basic issue. It would be greatly appreciated if someone could offer me some quick advice. So here's my dil ...

Combining one item from an Array Class into a new array using Typescript

I have an array class called DocumentItemSelection with the syntax: new Array<DocumentItemSelection>. My goal is to extract only the documentNumber class member and store it in another Array<string>, while keeping the same order intact. Is th ...

Split the string into individual parts and enclose each part in HTML using JavaScript

Currently, I am utilizing a content editable div to create tags. Upon pressing the return key, my objective is to select the preceding text (excluding the prior tags) and transform it into a new tag. The format for a tag will be enclosed within . For insta ...

Encountered a problem while parsing an XML file using JavaScript from an external server

Currently, I am developing an iPhone application in HTML that needs to pull content from an XML file stored on a remote server and display it in a list. I have successfully accomplished this task when the XML file is hosted on the same server using the fo ...

How can Angular provide a visual indication when a component change occurs?

Facing a dilemma as an Angular beginner... Imagine having an application that displays the most recent price of AAPL stock. You have a component where this price is received. Each time you request data from the API, a new price is retrieved and passed to ...

The email validation UI dialog is failing to display any dialog

<html> <head> <link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"& ...

What is the rationale behind requiring a semicolon specifically for IE11 in this function?

Currently, I am tackling some vuejs code to ensure compatibility with IE 11. Struggling with a persistent expected semicolon error in this particular function: chemicalFilters: function (chemical) { var max = 0; var min = 100; for (var ...