Is it possible for JsDoc to help me distinguish between milliseconds and seconds when I inadvertently confuse them?

Exploring TypeScript and JsDoc has been on my to-do list. Occasionally, I find myself mixing numeric values that aren't quite compatible. Let's consider a hypothetical situation where I mix milliseconds and seconds. In the script below, I've attempted to utilize JsDoc for guidance. While editing in Visual Studio Code, I expected to receive warnings or errors but nothing appeared.

// @ts-check

/** @typedef {number} TSseconds */
/** @typedef {number} TSmilliSeconds */

/** @type {TSmilliSeconds} */
let ms = 1;

/** @type {TSseconds} */
let sec = 2;

ms = sec;

/**
 * 
 * @param {TSseconds} secVal 
 * @returns {TSmilliSeconds}
 */
function sec2ms(secVal) {
    console.log("sec2ms", secVal);
    return 1000 * secVal;
}

/** @type {TSmilliSeconds} */
let ms2;
ms2 = sec2ms(ms);

/** @type {TSseconds} */
let sec2;
sec2 = sec2ms(ms);

It seems like I may have misunderstood something. How can I enhance the support from JsDoc here? (Code completion is functional.)

I currently have Typescript installed (npm install -g typescript) along with the latest stable version of NodeJs.

Answer №1

One way to enhance clarity when working with Typescript is by creating aliases for the number type to provide more descriptive names for function arguments. For instance:

type Seconds = number type MilliSeconds = number

function myTimer(arg0:Seconds, arg1:MilliSeconds){}

This approach helps to clearly define and differentiate between the values being passed into a function.

To further ensure correctness, you can implement a type helper that validates the input type as milliseconds like this:

type IsMilliSeconds<T> = T extends number
  ? `${T}` extends `${infer U}000`
    ? T
    : never
  : never;
  
function myTimerInMilliSeconds<T>(arg:IsMilliSeconds<T>){
  return arg
}

Here is a sample link showcasing how this can be implemented in Typescript code.

Using this method, if a function requires time in milliseconds but is given seconds instead, it would flag an error during myTimerInMilliSeconds(1).

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

Passing the value of a radio button to a component in React: a comprehensive guide

I've been struggling to figure out how to pass the value of a selected radio button to another component in React. Currently, I'm exploring the Star Wars API and attempting to create a basic search interface where users can retrieve information a ...

Combining and linking 3 RxJS Observables in TypeScript and Angular 4 without nesting to achieve dependencies in the result

I have 3 observables that need to be chained together, with the result from the first one used in the other 2. They must run sequentially and each one should wait for the previous one to complete before starting. Is there a way to chain them without nestin ...

Blocking of Reading Across Origins (BORAO)

After utilizing Jquery AJAX to call a third party API, I encountered the following error message in the console: Cross-Origin Read Blocking (CORB) blocked cross-origin response MY URL with MIME type application/json. For more information, visit . The A ...

Navigate through each file or image within a directory using Angular

I am facing a challenge with my app where each product has a gallery containing a random number of images, each with a completely unique name. These images are located in /src/assets/images/products/:id/. Currently, I am struggling to loop through and add ...

Issue: Anticipated the primary reducer to be a function, but was presented with: 'undefined' in Vanilla JS with Redux

Exploring the world of Redux, I decided to try out some code from a tutorial on YouTube. Building a simple Vanilla JS App, I integrated Redux into it. However, upon running the app in the terminal, an error message popped up saying: "Error: Expected the ro ...

When the object contains multiple arrays, filter out the id and remove it when clicked

I am working with an object that contains multiple arrays and aiming to filter out the id of the item to be removed onClick. However, I have encountered an error while trying to implement this logic. The error message I received is filter is not a functio ...

Is there a way to change the labels of checkboxes within a table that is created dynamically?

I am new to JavaScript/jQuery and facing an issue with modifying checkbox labels in a dynamically generated table. <td> <input type="checkbox> <b>$18,000.00</b> ($18000+) Diamond Sponsor<br> <input type="checkbox> <b ...

Issue with the functionality of a checkbox input placed inside a label

I successfully created a functioning checkbox: <div class="custom-control custom-switch mt-3 ml-4"> <input type="checkbox" class="custom-control-input" id='G1'> <label class="custom-cont ...

The current version of Aurelia in Karma does not support the use of Reflect.getOwnMetadata as a function

Since I updated to the most recent version of Aurelia (March update beta.1.1.4), I consistently encounter this error whenever I run karma tests: Error: Reflect.getOwnMetadata is not a function Error loading C:/Software/myproject/test/unit/myclass.spec.ts ...

Tips on streamlining the deployment process for a basic Vue WebApp without the need for a server (e.g. setting up a straightforward build chain with Vue

I have developed a Vue app and I am exploring ways to automate its deployment process by implementing a CI/CD pipeline that includes linting, testing, building, and uploading the files to web servers (such as stage or production using sftp). After researc ...

Together, we have a shared Yarn JS directory for both the client and server components,

The scenario: both the client and server share a folder named shared when we make changes to the shared folder in our development process, we need the corresponding references to update in both the client and server the server seems to w ...

Utilize JavaScript on the browser to send a post request to the Google API

I'm encountering a 404 error when making a $.ajax request to the Google API. Below are the codes I've been using: var asyncLoad = require('react-async-loader'); var CLIENT_ID = '<SOME_ID>'; var DISCOVERY_DOCS = ["https: ...

What is the best way to show the user profile on a Forum?

I am struggling to figure out how to display the username of a user on my forum page. I currently only have access to the user's ID and need help in extracting their name instead. It seems that I lack knowledge about mongoose and could really benefit ...

Ways to store extra user information in meteor.js beyond just the basic details, like their home address

Just starting out with Meteor.js, I decided to try my hand at creating a task list by following the tutorial on meteor.com. Adding the accounts-ui and accounts-password packages was a breeze, but now I'm looking to customize the sign-up process. In ad ...

jQuery validation: Form failing to pass validation

I have encountered an issue with a simple JavaScript file on my ASP.NET MVC website. While the input masking feature works smoothly, the form validation seems to be malfunctioning. Even when I enter a phone number that is only 4 digits long, the validation ...

Error in vis.js network: hierarchical layout caused by node quantity

I'm encountering an unusual issue that I can't seem to resolve by referring to the vis.js documentation. My network has a fixed hierarchy with a specific level defined for each node. I have a total of 51 nodes, and everything looks like this: ...

What is the best way to obtain the output of the MULTIPLO.SUPERIOR function using JavaScript?

In Microsoft Excel, there is a function called upper multiple where we can input a number and it will round up to the nearest multiple of a second specified number - for example: 10,986 ; 5 = 15 105,32 ; 5 = 110 ...

Data from Firebase persists even after removal

Currently utilizing firebase for my project, where each user object includes their list of favorites. The structure is illustrated below: https://i.sstatic.net/vm6w8.png In the favorites object shown, there was initially two records, but one was manually ...

Angular 2 - Graphic Representation Tool for Visualizing Workflows and Processes - Resource Center

Looking for a library that can meet specific requirements related to diagram creation and rendering. We have explored jsplumbtoolkit, mermaid, and gojs, but none of these fully satisfy our needs. For example, we need the ability to dynamically change con ...

Fuzziness occurrence in distinct vue element

My Situation I have a custom DropDown with a filter text input above. The DropDown can be opened independently from the filter text input. My Goal I want the DropDown to close when the filter input loses focus and also when I click outside of the Drop ...