The input value "HH:MM" does not match the expected format of 'FormatOptions' for this parameter

I created a function that takes in two parameters: data and format. I am attempting to define an ENUM(FormatOptions) for the "format" parameter. However, I encountered the following error:

Argument of type '"HH:MM"' is not compatible with parameter of type 'FormatOptions'

How can I correctly define the ENUM for the second argument? Check out the TypeScript Playground Here

Code:

const basicTime: any = {
  year: 'numeric',
  month: 'short',
  day: '2-digit',
  hour: 'numeric',
  minute: 'numeric',
};

const hoursMinutes: any = {
  hour: 'numeric',
  minute: 'numeric',
};

enum FormatOptions {
  HoursMinutes = 'HH:MM',
  MonthDayYear = 'MM/DD/YYYY',
};

const dateFormat = (date: Date, format: FormatOptions) => {
  if (format === 'HH:MM') {
    return new Date(date).toLocaleString('en-US', hoursMinutes);
  }

  return new Date(date).toLocaleString('en-US', basicTime);
};

dateFormat(new Date, 'HH:MM');

Answer №1

Swap out enum for union:

const basicTimeSettings: Intl.DateTimeFormatOptions = {
  year: 'numeric',
  month: 'short',
  day: '2-digit',
  hour: 'numeric',
  minute: 'numeric',
};

const hoursMinutesSettings: Intl.DateTimeFormatOptions = {
  hour: 'numeric',
  minute: 'numeric',
};


type TimeFormatOptions = 'HH:MM' | 'MM/DD/YYYY'


const formatTime = (date: Date, format: TimeFormatOptions) => {
  if (format === 'HH:MM') {
    return new Date(date).toLocaleString('en-US', hoursMinutesSettings);
  }

  return new Date(date).toLocaleString('en-US', basicTimeSettings);
};

formatTime(new Date(), 'HH:MM');

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

What are the distinctions between altering the value of a textarea with JS and user input?

I've come across an interesting scenario that I'm hoping someone with more expertise in JavaScript can help me with. There is a popular online forum site that I frequently use. In the past, I was able to easily update a comment textarea using Jav ...

Issue with jQuery click event not firing on multiple buttons with identical names

These are the two buttons that appear multiple times but do not function: <button name='btnEditar' class='btn btn-outline-success me-4' data-bs-toggle='modal' data-bs-target='#staticBackdrop'><i class=&a ...

Mastering the correct usage of Express middleware functions in routers

Displayed in this instance, are the csrfProtection and parseForm functions being utilized as parameters/callbacks within the GET and POST requests... var cookieParser = require('cookie-parser') var csrf = require('csurf') var bodyParse ...

Send two field values via axios by utilizing a b-form-select component from the Bootstrap Vue library

I'm struggling to send two fields to my backend, but every time I attempt to do so, both values end up as null in the backend. I am uncertain about what mistake I might be making. <template> <div id="app"> <div> ...

Adjust the color according to the chosen route in a Vue component

I am looking to dynamically change the CSS color based on the route or a prop for a route. For example, if I navigate to the home page, I want the header to be red. If I visit the about page, I want the header to be green. I have attempted this using rout ...

Creating an array of strings using data from a separate array of objects in JavaScript/TypeScript

I want to generate a new array of strings based on an existing array of objects, with each object belonging to the Employee class and having a firstName field: assignees: Array<Employee>; options: string[]; I attempted to achieve this using the fol ...

Unable to retrieve information obtained from MongoDB

After successfully retrieving all data from the "topics" collection using find() with cursor and foreach, I am encountering an issue. When I attempt to assign the fetched information to a variable named "data" and send it back to the page, it consistently ...

Articles related to Express.js - encountering issues when attempting to read properties from a null object

I'm trying to display related articles based on categories using Mongoose for querying data from MongoDB. However, when I attempt the code below, I encounter an error message stating "TypeError: Cannot read properties of null (reading 'category& ...

Is there a way to leverage JavaScript to click on one div and modify the settings of another div simultaneously?

I am struggling with my code which has unnecessary information. <div> <div id="one" class="button"></div> <div id="two" class="button"></div> </div> <div> <div class="Home tab"> < ...

What reasons could be preventing the state from updating correctly in Vuex?

Currently, I am working on a project where I am utilizing vuex along with axios to retrieve data from the backend. The issue arises when I try to access the state - even though the updated state is displayed successfully when I console-log it, there seems ...

The Jquery click event refuses to trigger

Below is the JavaScript code that is not functioning: $('#change-priority-modal').find('.btn-primary').unbind().on("click", function () { //my_func_body } Interestingly, the code works perfectly fine in the developer console. I would ...

Execute supplementary build scripts during the angular build process

I've developed an Angular application that loads an iframe containing a basic html page (iframe.html) and a Vanilla JavaScript file (iframe.js). To facilitate this, I've placed these 2 files in the assets folder so that they are automatically cop ...

Repurposing React key usage

section, I am curious to know if it is standard practice to reuse a React key from one component to another. For instance, in the Row component, the key obtained from the Column component is reused for mapping the children of Row. const Table = props =& ...

Error message "Property 'name' does not exist on type '{}'" is encountered when using Ionic/Angular HttpClient and no data type is specified

While working on my Ionic project, I encountered an error in Angular when trying to fetch data from an API using HttpClient. The error message that popped up was 'Property 'name' does not exist on type '{}'.'. Below is the cod ...

I am having issues with Hot Reload in my React application

My app was initially created using npx create-react-app. I then decided to clean up the project by deleting all files except for index.js in the src folder. However, after doing this, the hot reload feature stopped working and I had to manually refresh the ...

Is it possible to swap out the Firestore module `doc` with the `document` module

I enjoy using the Firebase version 9 modules, however, I find that doc is not to my liking. It would be better if it were document, similar to how collection is not shortened to col. The following code does not function as expected: import { doc, collecti ...

Pass on the touchmove event from the panel to the content using jQueryMobile

Within my interface, I have a link labeled myLink located in a side panel labeled myPanel, along with some content labeled myContent. My goal is to: Tap and hold on the link myLink within the panel myPanel Have the panel myPanel close immediately Add an ...

How can a row in AG-Grid be updated without causing a refresh?

I am working on adding a custom radio button feature for users to select a row. Currently, I have the following code: const Cell = (cellProps) => { const { data, node, api } = cellProps const selectedRow = () => { let { isChecked } = data ...

Switch up the color of the following-mouse-div in real-time to perfectly complement the color that lies underneath it

I am trying to create a div that changes color based on the complementary color of whatever is underneath the mouse pointer. I want it to follow the mouse and dynamically adjust its color. This functionality is similar to what Gpick does: https://www.you ...

Tips for typing a subset of an array containing string literals in TypeScript

Is it possible to have a function called createFields that takes a generic Object type, such as User, and extracts a subset of keys that can be inferred with a string literal array, similar to the selectable property in Fields? If so, how can this be ach ...