Leverage the same JSDoc comment across multiple TypeScript interfaces

If I have the interfaces below:

interface Foo {
  /**
   * A date string in the format `yyyy-MM-dd`
   */
  archiveDate: string;
}

interface Bar {
  /**
   * A date string in the format `yyyy-MM-dd`
   */
  publishDate: string;
}

The JSDoc descriptions for both interfaces are identical. Is there a method to centralize these descriptions and share them among multiple interfaces, eliminating the need for repetitive copying and pasting?

Answer №1

It can be argued that the JSDoc comment pertains to the type string in this case, rather than the property itself. This allows for defining a type alias and placing the documentation comment there.

/**
 * A date string in the format `yyyy-MM-dd`
 */
type DateString = string;

interface Foo {
  archiveDate: DateString;
}

interface Bar {
  publishDate: DateString;
}

Furthermore, you have the option to encode the format as a string literal type:

type Digit = '0' | '1' | '2' | '3' // | ... ;
type DateString = `${Digit}${Digit}${Digit}${Digit}-${Digit}${Digit}-${Digit}${Digit}`;

(the task of resolving the error

Expression produces a union type that is too complex to represent.(2590)
when adding the remaining digits is left as an exercise for the reader)

By using this approach, errors will surface when the specified format is not adhered to:

const foo: Foo = {
  archiveDate: '2023-1-1'
}
Type '"2023-1-1"' is not assignable to type '"0000-00-00" | "0000-00-01" | "0000-00-02" | "0000-00-03" | "0000-00-10" | "0000-00-11" | "0000-00-12" | "0000-00-13" | "0000-00-20" | "0000-00-21" | "0000-00-22" | "0000-00-23" | ... 65523 more ... | "3333-33-33"'. Did you mean '"2023-01-01"'?(2820)

Playground

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

As a quirk of TypeScript, it does not allow for returning a Tuple directly and instead interprets it as an Array

I need assistance with adding type-safe return to a general function created by a previous developer. Here is the current syntax: export function to(promise:Promise<any>) { return promise .then(data => [null, data]) .catch(err => [ ...

The Angular variable binding issue persists upon reloading the page or browser, yet functions seamlessly when navigating between routes

My subscribe button displays the text "Subscribe" when the page loads, but upon reloading the page, the text disappears. The button text is controlled by TypeScript code, and strangely, when I navigate to another route, the text magically reappears. HTML ...

Tips on getting the dropdown value to show up on the header when it changes using Angular 2 and TypeScript

I need assistance with creating a dropdown field in Angular2. When the user selects "car", I want it to display beside the heading. Can anyone provide guidance on how to achieve this? HTML: <h1>Heading <span *ngFor= "let apps of apps">({{apps ...

Angular, perplexed by the output displayed in the console

I'm completely new to Angular and feeling a bit lost when it comes to the console output of an Angular app. Let me show you what I've been working on so far! app.component.ts import { Component } from '@angular/core'; @Component({ ...

Guide to verifying the upcoming behavior subject data in Angular 8

I am facing an issue where I am attempting to access the next value of a BehaviorSubject in multiple components using a service. Although I can display the value in the UI using {{ interpolation }}, I am unable to see it in the console.log. Can someone hel ...

What is the process of declaring a react-icons icon in TypeScript?

Having a dilemma with declaring the icon in my array that contains name and icon. export const SidebarMenuList: SidebarMenu[] = [ { name: "Discover", icon: <AiOutlineHome />, id: SidebarCategory.Discover, }, ] The SidebarMe ...

The cause of Interface A improperly extending Interface B errors in Typescript

Why does extending an interface by adding more properties make it non-assignable to a function accepting the base interface type? Shouldn't the overriding interface always have the properties that the function expects from the Base interface type? Th ...

My function won't get called when utilizing Angular

My Angular code is attempting to hide columns of a table using the function shouldHideColumn(). Despite my efforts, I am unable to bind my tags to the <th> and <td> elements. An error keeps popping up saying Can't bind to 'printerColu ...

Angular 8 and Bootstrap 4 Integration: Navbar Functionality Working, but Issue with Auto-Closing on Click Action (Both Inside and Outside Navbar)

While using ng-bootstrap with Angular 8, I encountered a problem with the navbar. The navbar functions properly by being responsive and opening/closing when clicking the hamburger icon. However, the issue arises when it does not automatically close when a ...

Creating type definitions for TypeScript (ts) involves defining the shape and

Having trouble using a library installed in node_modules/ within a typescript app? Here's a quick hack for you. Create a folder named after the module in typings/modules and add an index.d.ts file inside with the following content: declare module "li ...

In Next.js, a peculiar issue arises when getServerSideProps receives a query stringified object that appears as "[Object object]"

Summary: query: { token: '[object Object]' }, params: { token: '[object Object]' } The folder structure of my pages is as follows: +---catalog | | index.tsx | | products.tsx | | | \---[slug] | index.tsx | ...

Utilizing props in styled components with Emotion-js and Typescript is not feasible

Check out this simple React component I created: import React, { ReactChild, ElementType } from 'react' import styled from '@emotion/styled' type WrapperPropsType = { size?: SizeType } type ButtonPropsType = { as?: ElementType< ...

Achieving a similar functionality to Spring Security ACL in a Node.js AWS Lambda serverless environment

I am tackling a javascript challenge that has me stumped. Specifically, I am trying to figure out how to implement fine-grained authorization using an AWS serverless approach. In Spring security ACL, users can be banned from specific tasks at the instanc ...

Angular 8 template-driven form encountering a Minimum Length Error

Upon clicking the submit button, I encountered the following error: ERROR TypeError: Cannot read property 'minlength' of null I am unsure why this error is happening. How can I go about resolving this issue? Below is the code from app.componen ...

Using the keyof operator to determine the data type of a property within a TypeScript class

According to TypeScript's documentation on the keyof operator, you can access a property of an object instance using this function below. function getProperty<T, K extends keyof T>(o: T, name: K) { return o[name]; } If you want to obtain th ...

What is the best approach to implement a recursive intersection while keeping refactoring in consideration?

I'm currently in the process of refactoring this code snippet to allow for the reuse of the same middleware logic on multiple pages in a type-safe manner. However, I am encountering difficulties when trying to write a typesafe recursive type that can ...

Guidelines for cycling through a series of HTTP requests and effectively saving the data from each cycle into an array

Utilizing Spotify's API search feature, I am working with an array of SongSearchParams that consist of title and artist parameters: export class SongSearchParams { public title: string; public artist: string; constructor(title: string, a ...

My Angular2+ application is encountering errors with all components and modules displaying the message "Provider for Router not found."

After adding routing to my basic app through app.routing.ts, I encountered errors in all of my test files stating that no Router is provided. To resolve the errors, I found that I can add imports: [RouterTestingModule], but is there a way to globally impo ...

Giving the function parameter dynamic type depending on the first parameter

Currently, I have a basic function that my client uses to communicate with my server. In order to maintain flexibility, I have implemented the following: public call(method: string, ...parameters: any[]) {} On the server side, I organize all methods toge ...