Using moment-duration-format in TypeScript: A step-by-step guide

In my TypeScript (Ionic2/Angular2) project, I have incorporated moment.js. After reading through this post, I decided to experiment with a plugin called moment-duration-format

With the npm package and type definition installed, I can use it by importing as..

import moment from 'moment';
...
let duration = moment.duration(decimalHours, 'hours');

Now, I want to dive into using moment-duration-format

I went ahead and installed it using

npm install moment-duration-format --save
followed by adding the type definition with
npm i @types/moment-duration-format --save
.

Both npm modules are in place.

However, there seems to be some confusion on how to actually utilize these type definitions (the documentation lacks clarity on this aspect).

I attempted to add import 'moment-duration-format'; and

import duration from 'moment-duration-format';
but encountered errors as such..

let dd = moment.duration.format(400.99, 'hours').format('D:HH:mm');

// Error - Property 'format' does not exist on type '(inp?: DurationInputArg1, unit?: DurationConstructor) => Duration'.

If anyone has insights on how to effectively leverage this in TypeScript, your help would be greatly appreciated.

Thank you in advance

Answer №1

Previously, I employed a workaround mentioned here. However, it appears that the type definition issue has been resolved now. I am looking forward to updating the type definition so that I can proceed with the following code snippet...

import * as moment from 'moment';
import 'moment-duration-format';

let duration = moment.duration(decimalHours, 'hours') ;   
let options : moment.DurationFormatSettings   = {
  forceLength : false,
  precision : 0,
  template : formatString,
  trim : false
};
let result  = duration.format(formatString, 0, options);

Answer №2

Instead of calling duration as a method, you are using it as a property. Try this approach:

let dur = moment.duration(400.99, 'hours').format('D:HH:mm');

This issue is not specific to TypeScript; even in JavaScript, this would result in a runtime error. TypeScript catches this error at compile time, showcasing its value.

Answer №3

I've encountered a similar issue...

It appears that there may be a mistake in the type definition. Many others are experiencing the same problem, as evident here: https://example.com/type-definition-error

A solution was proposed for this issue in a pull request on GitHub, but unfortunately, it was closed without being merged: https://example.com/pull-request-fix

For now, you could try using the code snippet from the first link as a temporary fix. In the next step, we should consider creating a new pull request on GitHub to address this problem in upcoming releases.

Answer №4

The issue arises from an incorrect type definition within the typings module for moment-duration-format, as correctly identified by R_B_.

To address this issue, a new pull request will be submitted, following the closure of the previous one due to lint errors.

In the meantime, a workaround is available by utilizing a custom type definition in your project, similar to the approach taken here: https://github.com/TwoStone/leaderboard/blob/develop/subprojects/webapp/src/custom-typings.d.ts Simply create the file within your project, and it should provide a temporary solution.

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

Utilizing the Vuetify Dialog Component in a repetitive manner to confirm the deletion of an event

In a project I'm working on, there's a 'datatable.vue' file that loops through data and displays it in a table. Within this loop, I want to implement a reusable dialog component from Vuetify (v-dialog) that will load upon interaction wi ...

Update the field's status to non-editable when the radio button is chosen, without using jQuery

My form contains a mix of normal and read-only fields. Additionally, there is a radio button with two options. If the default option is selected, nothing changes. However, if the second option is chosen, the read-only fields should become editable. The ch ...

Getting data for Selectize.js

I've implemented Selectize.js to create a tagging feature for assigning users to jobs, utilizing the existing users within the system. In my scenario Following the provided documentation, I have included a select box with the multiple attribute that ...

Error in TypeScript when utilizing generic callbacks for varying event types

I'm currently working on developing a generic event handler that allows me to specify the event key, such as "pointermove", and have typescript automatically infer the event type, in this case PointerEvent. However, I am encountering an error when try ...

What is the best way to update the value of a specific key in discord.js?

As I struggle to explain properly due to my limited English proficiency, I am reiterating my question. In my config.json file, there is a key named "status" with a corresponding value of "online". I am attempting to change this value but haven't been ...

Unable to verify the value type of mat-autocomplete using the [displayWith] directive

When using mat-autocomplete, the feature [displayWith] is utilized to format the value and provide some functionality. This raises the following questions: 1. What exactly is the purpose of [displayWith]? Can it be used to validate the type of text entere ...

In Bootstrap 5, clicking inside a dropdown should not cause it to open or close unexpectedly

Check out the code snippet below: <html> <head> <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7d1f1212090e090f1c0d3d48534e534e">[email protected]</a>/d ...

Is there a way to modify the CSS or add custom styling within an iframe form?

Currently I am working on the following page: , where an embedded javascript form called infusionsoft (iframe form) needs to be made responsive at the request of my client. I'm wondering if there is a way to override the css or inject custom styles i ...

Using Typescript and Knockout.js in an MVC application: A simplified guide

Having Trouble Binding a Knockout.js ViewModel to MVC Despite attempting to follow multiple tutorials, none of them seem to be working for me. I have not encountered any errors while building the app, but the results are not as expected. Here is my TS fi ...

The personalized directive does not respond to modifications in attributes

I am in the process of creating a modal directive that will be used to display data tables. The directive has an attribute called modal-visible, which is initially set to false by default. If this value is true, the modal will be visible when loaded. Howev ...

Challenges faced with implementing Tailwind CSS within the pages directory of NextJS websites

Issue with Tailwind Styles I've encountered a problem where the Tailwind styles are not being applied to components in the /pages directory of my NextJS project. Oddly enough, the same component works fine when used outside the pages directory. When ...

Is it possible to convert an array into an object?

I'm attempting to restructure an array of objects into a new object where the label property serves as the key for multiple arrays containing objects with that same label. Check out this JSBin function I created to map the array, but I'm unsure ...

I'm trying to resolve the "Uncaught TypeError: Cannot read property '0' of null" error that keeps popping up in my Mobx action within a Firebase and React application. Can anyone offer some guidance on

I've encountered some errors while working on a Mobx React application that occurs when I navigate to the /login page, despite being logged in. Here's a snippet of my code: index.tsx (Code Snippet Here) App.tsx (Code Snippet Here) Login.tsx ...

What are some ways to alleviate tension on the left side of the body

Currently, I am working on implementing a pop-out menu, and have encountered a small issue. I've added the following styling: .menu-side, .menu { -webkit-transition: left 0.2s ease; -moz-transition: left 0.2s ease; transi ...

Issues with the Injector arise during the Angular 2 RC5 to RC6 migration

After smoothly running my Angular2 RC5 application, I decided to upgrade to RC6. However, upon doing so, my application ceased functioning and displayed the following error message: Error: Can't resolve all parameters for LoginComponent: (?, ?). M ...

There was an unexpected error: The module "@angular-devkit/build-angular" could not be located

After entering the terminal commands ng server or ng serve, I encountered the following problem: An unexpected error occured: Module "@angular-devkit/build-angular" could not be located ...

Tips for implementing Undefined validations with Lodash

When receiving nested objects in the response, we must traverse to the property and display the values in the user interface. If we have a nested object like this: obj = { parent: { innerchild1: { innerchild2:{ displayText: ...

Guide to fetching input control value dynamically inserted via javascript

In my PHP view, I have implemented a button that adds textboxes to the page within a form. However, when trying to retrieve the value of these dynamically added textboxes in my PHP controller, the value is not present. Is there a solution for obtaining t ...

Tips for transferring information from a controller to a directive using the $emit method

I am facing an issue passing values from the controller to the directive Within my controller, I have two arrays defined as: $scope.displayPeople.push(data.userName); $scope.displayOrg.push(data.orgname); I need to pass these arrays from the controller ...

Unable to shrink array within an object

I'm encountering an issue while trying to reduce an array within an object. The error message I receive is: push is not a function To begin, I initialized my arrays as empty and created an add function to use as the first argument: function add(a,b ...