Typescript encounters Duplicate error when method overloading is implemented

Below is the code snippet that I am working with:

public async insert(data: iFlower | iFlower[]): Promise<iFlower> | Promise<iFlower[]> {
 await this.insert(data);
}

private async insert(data: iFlower): Promise<iFlower>{
 ....
 return data;
}

private async insert(data: iFlower[]): Promise<iFlower[]> {
 ....
 return data;
}

The structure of iFlower is defined as follows:

export interface iFlower {
   color: string;
   number: string;
}

When attempting to run the code, the following errors are encountered:

The return type of an async function or method must be the global Promise<T> type.
Duplicate function implementation.
'insert' is declared but its value is never read.

Could these errors stem from using iFlower as an interface?

Answer №1

When using method overloading in TypeScript, the key aspect to remember is that you are providing multiple type definitions while the actual implementation remains a single function. This means that you define different input types for the function and then have one unified implementation that caters to all those types, like so:

private async add(item: Item): Promise<Item>;
private async add(item: Item[]): Promise<Item[]>;
private async add(item: Item | Item[]): Promise<Item> | Promise<Item[]> {
  // Your logic goes here. For example:
  if (Array.isArray(item)) {
    ... 
    return item;
  } else {
    ... 
    return item;
  }
}

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

Is the regex returning the correct result?

I need to discuss the date field with a format of YYYYMMDD, as shown below: zod.string().max(8).regex(new RegExp('^(19[0-9][0-9]|20[0-9][0-9]|[0-1][0-9]{3})(1[0-2]|0[1-9])(3[01]|[0-2][1-9]|[12]0)$')); The value provided is 20001915. The definit ...

When a node_module package includes type imports, Next.js can encounter build failures during the linting and type validity checking processes

This NextJS 13 project utilizes a package that has an inner core dependency (react-leaflet->@react-leaflet/core). When running yarn run build, the build fails at "Linting and checking validity of types." It appears to be a TypeScript compatibility iss ...

Leveraging Class Types with Generics

Take a look at this example: https://www.typescriptlang.org/docs/handbook/2/generics.html#using-class-types-in-generics To make it work, I just need to call a static method before instantiation. Let's adjust the example like this: class BeeKeeper { ...

TS2604: The JSX element '...' lacks any construct or call signatures and is unable to be processed

As part of our company's initiative to streamline development, I am working on creating a package that includes common components used across all projects. We primarily work with TypeScript, and I have successfully moved the code to a new project that ...

Changing the default route in Angular 2 based on conditions

I'm currently developing an application where, upon entering the page, the default route for the user is the "Login" page. However, I want to implement a condition based on whether the user has a local storage variable (id) set. If this variable exist ...

What is the method to insert a new <input> element after the last input field has been filled in

I recently started working on a form using StackBlitz, but I've hit a roadblock and need some guidance on how to proceed. My goal is to achieve a similar effect like the one shown in this gif: https://i.stack.imgur.com/76nsY.gif and I'd like to ...

Error: The variable "document" is not defined in the context of NextJS TypeScript

Here is the import trace for the requested module: ./app/StarrySky.tsx ./app/resume/page.tsx ✓ Compiled in 425ms (711 modules) ⨯ app\StarrySky.tsx (9:4) @ document ⨯ ReferenceError: document is not defined Trying to set const vw equal to the ma ...

Leveraging React Hooks to display a dynamic pie chart by fetching and mapping data from an API

I have a task where I need to fetch data from an API that returns an object containing two numbers and a list structured like this... {2, 1 , []} The project I'm currently working on utilizes 'use-global-hook' for managing state in Redux. T ...

Empty initial value of a number type input element in React using TSX

In the process of developing a react POS app using Typescript, I encountered an issue with calculating change when entering the amount of money received from a buyer. The problem arises when the first value passed to the change calculation logic is empty, ...

Best Practices for Error Handling in Typescript

After delving into articles about error handling, a thought lingers in my mind - is throwing an exception on validation logic in the value object really the most efficient approach? Take for example this class that represents a value object: export class U ...

What are some ways to prevent unnecessary HTML re-rendering when using this.sanitizer.bypassSecurityTrustHtml(value)?

What is the best way to prevent constant HTML re-rendering when utilizing (this.sanitizer.bypassSecurityTrustHtml(value)) in Angular versions 5 and above? ...

When viewing a React data table in Chromium browsers, the columns on the right side may flicker when the screen is small or the browser

I recently integrated the React data grid Npm package by adazzle. You can find more information about it here. I encountered an issue which you can see in this example: https://codesandbox.io/s/react-data-grid-example-9sb93?file=/src/App.tsx When using a ...

Steps for updating the same array in TypeScript

I have written a reducer code where I check if the same value is already present in the array. If it is, I update the previous value instead of pushing the same value again. Here is my code snippet: export function reducer( state: IDeviceState = ...

Checking the formik field with an array of objects through Yup for validation

Here is a snippet of the code I'm working on: https://codesandbox.io/s/busy-bose-4qhoh?file=/src/App.tsx I am currently in the process of creating a form that will accept an array of objects called Criterion, which are of a specific type: export inte ...

Calculating Events with the onChange Method in Typescript

How do I calculate the total ticket price when I adjust the number of individuals? HTML Code : <div class="row"> <div class="col-md-6"> <label for="person">Person</label> <div class="form-group"> ...

Issue with Angular 7: "Unspecified name attribute causing control not found"

As I delve into the creation of my initial Angular application, I find myself faced with a series of errors appearing in the development mode console: ERROR Error: "Cannot find control with unspecified name attribute" ERROR Error: "Cannot f ...

What is the reason TypeScript struggles to automatically deduce assignments of identical object types?

Imagine a scenario with a simple code snippet to illustrate the issue: interface I { n?: number; s?: string; } const a: I = { n: 1, } const b: I = { n: 2, s: 'b', } const props = ['n', 's'] as const; for (const p ...

Create a custom data structure resembling a record, where certain keys are assigned specific value types

My objective is to establish a custom type resembling a record, where certain keys are designated for specific value types. The proposed object would look something like this: const o: TRec = { text: "abc", width: 123, height: 456, //...an ...

Why is TypeScript unable to recognize package exports? (using CommonJS as the module system and Node as the module resolution)

I have an NPM package that is built for ESM and CJS formats. The package has a dist folder in the root directory, which contains: dist/esm - modules with ESM dist/cjs - modules with CJS dist/types - typings for all modules In the package.json file, there ...

Typescript Support in Goland IDE for HTML Documents

I'm currently utilizing Go for my programming tasks, and I prefer the Goland IDE developed by Jetbrains. Is there a way for me to incorporate typescript into my .html template files that contain a mix of HTML, CSS, and JS? Your assistance is much ap ...