Typescript error: The overload signature does not match its implementation signature

I am facing an issue with the code below. It seems to work fine without including setCurrentTab in the return interface useTabsReturnType, but as soon as I add it, the code stops working and I'm not sure why.

interface useTabsReturnType<T> {
  currentTab: T;
  setCurrentTab: React.Dispatch<React.SetStateAction<T>>;
}

export function useTabs(defaultValues: number): useTabsReturnType<number>;
//This overload signature is not compatible with its implementation signature.ts(2394)
export function useTabs(defaultValues: string): useTabsReturnType<string>;
export function useTabs(defaultValues?: string | number): useTabsReturnType<string | number> {
  const [currentTab, setCurrentTab] = useState(defaultValues || '');

  return {
    currentTab,
    setCurrentTab,
  };
}

edit: after following Radu Diță's suggestion I got this error:

Type 'Dispatch<SetStateAction<string | number>>' is not assignable to type 'Dispatch<SetStateAction<string>> | Dispatch<SetStateAction<number>>'.
  Type 'Dispatch<SetStateAction<string | number>>' is not assignable to type 'Dispatch<SetStateAction<string>>'.
    Type 'SetStateAction<string>' is not assignable to type 'SetStateAction<string | number>'.
      Type '(prevState: string) => string' is not assignable to type 'SetStateAction<string | number>'.
        Type '(prevState: string) => string' is not assignable to type '(prevState: string | number) => string | number'.
          Types of parameters 'prevState' and 'prevState' are incompatible.
            Type 'string | number' is not assignable to type 'string'.
              Type 'number' is not assignable to type 'string'.ts(2322)
useTabs.ts(20, 3): The expected type comes from property 'setCurrentTab' which is declared here on type 'useTabsReturnType<number> | useTabsReturnType<string>'

The error came from here:

return {
  currentTab,
  setCurrentTab,
  ^^^^^^^^^^^^^
};

Answer №1

Have you considered making your useTabs function more versatile?

export function useTabs<T extends string | number>(initialValue: T): useTabsReturnType<T> {
  const [activeTab, setActiveTab] = useState(initialValue);

  return {
    activeTab,
    setActiveTab,
  };
}

Answer №2

If you're looking for a quick solution, consider adjusting the return type in the function's implementation. Here's an example:

export function useTabs(defaultValues?: string | number): useTabsReturnType<string> | useTabsReturnType<number> {
  const [currentTab, setCurrentTab] = useState(defaultValues || '');

  return {
    currentTab,
    setCurrentTab,
  };
}

Pay attention to the change from

useTabsReturnType<string | number>
to
useTabsReturnType<string> | useTabsReturnType<number>

Alternatively, you can utilize type and let TS distribute the union. Take a look at this example:

type useTabsReturnType<T> = T extends any ? {
  currentTab: T;
  setCurrentTab: React.Dispatch<React.SetStateAction<T>>;
} : never

This approach allows you to keep the function's return type unchanged.

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

Issue with ng-multiselect-dropdown where clearing selected items programmatically does not visually work as expected

Utilizing the ng-multiselect-dropdown, I have encountered an issue where deselecting an option within the object itself clears the selected items visually and in the variable array. However, when programmatically clearing the selectedItems, the variable a ...

Experiencing a type error within Redux in a React Native project utilizing TypeScript

I am currently working on implementing a feature to store the boolean value of whether a phone number is verified or not. Within my login component: await dispatch(setOTPVerified(data.is_phone_verified)); Action.tsx: export const OTP_VERIFIED = 'OTP ...

Steps for referencing a custom JavaScript file instead of the default one:

Currently, I am utilizing webpack and typescript in my single page application in combination with the oidc-client npm package. The structure of the oidc-client package that I am working with is as follows: oidc-client.d.ts oidc-client.js oidc-client.rs ...

Translate JSON to TypeScript class. If the property is an object and not present in the JSON, the class should contain an empty object

I am having trouble finding an appropriate title for the issue I am currently facing. Therefore, I will provide a detailed explanation of the problem. I have a class named Model.ts export class Model{ a:ObjA; b:ObjB; c:ObjC; d:string; ...

Guide to accessing a newly opened window from a different domain originating from the current window

Currently working on an Angular project, I am facing a scenario where I have a link on page A that directs users to a different origin page B. The HTML code for the link is shown below: ... <a href="https://another.origin"> PAGE B </a> ... On ...

What causes the cursor in an editable div to automatically move to the front of the div?

<div className="min-w-[600px] min-h-[36.8px]" > <div id={`editableDiv-${Object.keys(item)}-${index}`} className="p-3" contentEditable suppressContentEditableWarning onInput={(e) => onChange(e)} > ...

Troubleshooting Issues with MUI MultiSelect Dropdown in TypeScript: Unable to Select or Update Values

I've been attempting to create a multiselect dropdown list with checkboxes. The items in the dropdown are coming from an API call, and I'm trying to update a set of values to save back to the database. While I've succeeded in populating the ...

Error encountered during compilation while attempting to import a JSON file in Angular 7

One great aspect of angular 7 is its compatibility with typescript 3.1: https://alligator.io/angular/angular-7/ I have made the following changes to the tsconfig.json file, within the 'compilerOptions' section: "resolveJsonModule": true, "esMo ...

What is the best way to utilize the code generated by @graphql-codegen for fetching a single record?

After following the steps in the getting started guide, I now have a code file that was generated from an existing federated graph that has been deployed. The generated code includes: export type Query = { __typename?: 'Query'; customerById: ...

Is it possible to retrieve a constant value while developing a customized rule in typescript-eslint?

I am currently working on implementing a custom ESLint rule using @typescript-eslint/utils that will display a warning if the prop kind of Category does not match a specific Regex pattern: import { ESLintUtils, TSESTree } from '@typescript-eslint/util ...

Utilizing ES6 Promises in Mongoose with Typescript to Create a Seamless Chain

When attempting to chain ES6 promises with Mongoose 4.5.4, I encountered an error in Typescript. public static signup(req: express.Request, res: express.Response) { UserModel.findOne({ email: req.body.email }).exec() .then(existingUser => { ...

Enhance the annotation of JS types for arguments with default values

Currently, I am working within a code base that predominantly uses JS files, rather than TS. However, I have decided to incorporate tsc for type validation. In TypeScript, one method of inferring types for arguments is based on default values. For example ...

Defined a data type using Typescript, however, the underlying Javascript code is operating with an incorrect data type

Recently delving into Typescript and following along with an educational video. Encountered a strange behavior that seems like a bug. For instance: const json = '{"x": 10, "y":10}'; const coordinates: { x: number; y: number } = JSON.parse(json); ...

ng namespace not found

I am currently in the process of converting a simple Angular 1.6 project to TypeScript. I have declared all the necessary typings dependencies and they have been compiled and installed successfully. However, I am encountering a compilation error stating "C ...

How can I indicate separate paths for the identical dependencies listed in package.json?

Currently, I am in the process of working on an npm package that consists of an example directory designed to run and test the actual package. Within this example directory, I have re-integrated the parent package using "file:..". While this set ...

Bringing in a service from a different module in NestJS

Having an issue trying to utilize the surveyService within the voteOptionRepository. When attempting to use the route, the console displays: TypeError: this.surveyService.getSurveyById is not a function Below is my SurveyModule setup: @Module({ im ...

Getting the value from an array of objects in React Redux Toolkit

Task: const postsData = useSelector((state: RootState) => state.postsSlice.posts); { postsData?.map((post) => { return ( <PostCard key={post.id} title={post.title} description={post.body} user={post.use ...

TS2339 Error: The property 'Default' is not a valid property for type 'string'

Hello, I am a beginner with Angular 2. I have encountered some issues that I need help with: Error Messages: app/components/playing-cables/-update.ts(82,12): error TS2339: Property 'options' does not exist on type 'jQuery'. app/compone ...

When attempting to assign a 'string' type to the @Input property, I am receiving an error stating that it is not assignable to the 'PostCard Layout' type

Encountering an issue The error message 'Type 'string' is not assignable to type 'PostCard Layout'' is being displayed A parent component named page-blog.component.html is responsible for defining the class styles and passi ...

In TypeScript, is it possible to indicate that a function will explicitly define a variable?

In TypeScript, I am working on creating a class that delays the computation of its information until it is first requested, and then caches it for future use. The basic logic can be summarized as follows. let foo: string | undefined = undefined; function d ...