Avoid using `object` as a data type, as it can be challenging to work with

const useSetState = <T extends dataStructure>(
  initialState: T = {} as T
): [T, (patch: Partial<T> | ((prevState: T) => Partial<T>)) => void] => {
  const [state, setState] = useState<T>(initialState);
  const setMergeState = useCallback(
    (patch) => {
      setState((prevState) => ({
        ...prevState,
        ...(patch instanceof Function ? patch(prevState) : patch),
      }));
    },
    [setState]
  );

  return [state, setMergeState];
};

However, an issue arose: Avoid using dataStructure as a type. The dataStructure type can be challenging to work with (see this issue).

https://i.sstatic.net/MEdbi.jpg

Answer №1

The concept of object type has become obsolete as everything in JavaScript is treated as an object. Instead of specifying object type, simply use {} which will accept any properties. When referring to anything in general, utilize any. However, since everything essentially falls under the category of an object, defining a main any property for all objects seems redundant. Therefore, TypeScript now opts to disable type checking for this purpose.

Given that everything is considered an object, there is no need to use extends object. Stick to using just T.


But why does everything classify as an object? Both JavaScript and TypeScript have always embraced object-oriented programming principles. Unlike languages like Java that follow a class-based approach, JS primarily relies on prototypes. Every value within TS/JS derives from the Object class, much like in Java and C#. Objects possess properties similar to those found in strings - for instance, you can apply "string".toUpperCase(). This rule applies to numbers, instances of classes (new XMLHttpReqeust), static classes (Math), literal objects without properties ({}.hasOwnProperty), arrays, and various other entities.

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

It appears that Yarn is having trouble properly retrieving all the necessary files for a package

Recently, I encountered a strange issue in our project involving 3 microservices, all using the exceljs library. Two of the microservices successfully download all necessary files for this package through yarn. However, the third microservice is missing ...

Generate ES6 prototypes using TypeScript

Is it possible to enhance specific class methods in TypeScript by making them prototypes, even when the target is ES6? Additionally, can a specific class be configured to only produce prototypes? Consider the following TypeScript class: class Test { ...

Navigating to a Different Page in Angular 7

After logging in on my login page, the dashboard component appears below the login page instead of redirecting as a new page. How can I achieve this in Angular 7? Any assistance would be greatly appreciated. Thank you! app.component.ts import { Component ...

Guide on setting up redux store from server component using next.js and app router

I'm currently working with Next.js 13, React, and Redux to handle state management. My main objective is to fetch initial data on the server side and present it on the client side. Although I assumed this would be a typical approach with Redux and Ne ...

How can I ensure my function waits for a promise to be resolved using Async / Await?

I'm running into an issue where I want my function to keep executing until the nextPageToken is null. The problem occurs when the function runs for the first time, it waits for the promise to resolve. However, if there is a nextPageToken present in th ...

The browser failed to display the SVG image, and the console log indicated that the promise was rejected, with the message "false."

I'm struggling to understand why my SVG isn't showing up on the screen. The console log is displaying "false," which I believe indicates that a promise was rejected Here is the TypeScript file I am working with: export class PieChartComponent im ...

What is the reason for Typescript's compatibility with WScript?

Recently, I decided to install Typescript in order to get WScript intellisense in VScode. After setting it up, I was able to achieve the desired intellisense. However, I encountered an issue when compiling a Typescript file containing a WScript method usin ...

How to upgrade Angular Header/Http/RequestOptions from deprecated in Angular 6.0 to Angular 8.0?

When working on http requests in Angular 6.0, I typically follow this block of code. https://i.sstatic.net/XsSv9.png I attempted to incorporate the newer features introduced in Angular 8.0 such as HttpClient, HttpResponse, and HttpHeaders. However, I fou ...

Is the detection change triggered when default TS/JS Data types methods are called within an HTML template?

I'm currently updating an application where developers originally included function calls directly in the HTML templating, like this: <span>{{'getX()'}}</span> This resulted in the getX method being called after each change dete ...

Securing redirection in WebPart using Azure AD: Best practices

I've successfully created a Sharepoint Webpart with a straightforward goal: authenticate users on an external website embedded within Sharepoint. This external site utilizes Azure AD for user logins. However, my current implementation has a significa ...

Enforce boundaries by constraining the marker within a specified polygon on a leaflet map

Currently, I am utilizing a leaflet map to track the user's location. The map includes a marker for the user and a polygon shape. My goal is to ensure that the user marker always stays within the boundaries of the defined polygon. In case the user mov ...

What is the best way to restrict the key of an object type to only be within a specific union in TypeScript?

I need to create a set of server types in a union like this: type Union = 'A' | 'B' | 'C'; After that, I want to define an object type where the keys are limited to only certain options from this Union: // Use only 'A&ap ...

Is it possible to utilize Angular translate to support multiple languages for individual components or modules?

Utilizing ngx-translate to switch the language of my application has proven to be quite challenging. My application consists of different languages specifically for testing purposes and is divided into separate modules with lazy loading functionality. As ...

"Step-by-Step Guide: Displaying a New Component When a Table Row is

I am currently working with an API to populate a table within the router outlet, but I would like to know how I can load a different component that displays the details of a selected row. For example, if the table contains a list of equipment, I want to be ...

Preventing the automatic selection of the initial item in a PrimeNG dropdown menu

While utilizing the p-menu component from PrimeNG in popup mode ([popup]="true"), I encountered an unexpected issue where the first item in the menu is automatically selected and turns gray. Here is the code snippet that I am using: <p-menu #menu [popu ...

Having trouble with Angular Ng2-file-Upload's Upload.all() method not successfully sending files to the API

Dealing with the challenge of uploading files in mp4 and jpg formats, I have set up 2 separate instances of FileUploader with custom validation. Upon clicking the upload button, I attempt to merge the files from both instances into a single FileUploader ...

Help with Material-UI: Passing unique props to a custom TreeItem component

I am trying to pass an argument category to the component CustomTreeItem which uses TreeItemContent. Documentation: https://mui.com/ru/api/tree-item/ import TreeItem, { TreeItemProps, useTreeItem, TreeItemContentProps, } from '@material-ui/lab ...

Discovering ways to optimize argument type declarations in TypeScript

If we consider having code structured like this: function updateById( collection: Record<string, any>[], id: number, patch: Record<string, any> ): any[] { return collection.map(item => { if (item.id === id) { return { ...

Is there a way to deactivate a tab when it's active and reactivate it upon clicking another tab in Angular?

<a class="nav-link" routerLink="/books" routerLinkActive="active (click)="bookTabIsClicked()" > Books </a> I am currently teaching myself Angular. I need help with disabling this tab when it is active ...

The issue with Angular 2's router.navigate not functioning as expected within a nested JavaScript function

Consider the app module: import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { RouterModule } from '@angul ...