0

I am trying to create a Typescript definition file for format-duration:

module.exports = (ms) => {
  let { days, hours, minutes, seconds } = parseMs(ms)
  seconds = addZero(seconds)
  if (days) return `${days}:${addZero(hours)}:${addZero(minutes)}:${seconds}`
  if (hours) return `${hours}:${addZero(minutes)}:${seconds}`
  return `${minutes}:${seconds}`
}

I have tried a few different declaration files:

export default function (ms: number): string;

export default function formatDuration(ms: number): string;

export function formatDuration(ms: number): string;

and whilst I do get the correct type information from them when I run the application I get an error:

import formatDuration from "format-duration";

const formatted = formatDuration(123456);

Exception has occurred: TypeError TypeError: format_duration_1.default is not a function

How do I properly define types for this sort of javascript library?

3
  • Which one of the export statements give you the half output? Commented Nov 29, 2017 at 21:19
  • I don't know if it's possible to type a nameless export? In the other cases you should be able to use declare formatDuration:(ms:number):string Commented Nov 29, 2017 at 21:36
  • You should read this first -typescriptlang.org/docs/handbook/modules.html#import Commented Nov 29, 2017 at 22:09

1 Answer 1

1

It seems that the correct declaration file looks like this:

declare function formatDuration(ms: number): string;

export = formatDuration;

and it is imported like this:

import formatDuration = require("format-duration");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.