Avoid utilizing object as a data type

Currently, I am encountering a lint error that states:

Avoid using object as a type

My code snippet where I use object as a type can be seen below:

export const myFunc = (obj: object): string => {
  return obj.toString()
}

I'm looking for suggestions on what type to assign to an object with unknown properties.

Just to clarify, the object in question is not an array (which we know is technically still considered an object in JavaScript).

Thanks in advance for any insights!

Answer №1

There are multiple approaches to solve this issue. Personally, I believe that the necessity for it may be considered somewhat of an anti-pattern.

However, my recommended choice would likely be using Record<string, any>. Hopefully, this solution works well for your needs.

Answer №2

In my opinion, the most effective approach in this situation is to utilize a generic:

export const customFunction = <T extends { toString: () => string }>(input: T): string => {
    return input.toString()
}

customFunction(2) // no issues
customFunction({}) // no issues

If you wish to restrict your parameters to only objects, then indeed, @Evert's solution is suitable. However, for better type safety, it is recommended to use unknown instead of any:

Record<string, unknown>

Answer №3

Let's take a practical example to understand why the coding convention discourages using the object type:

function sampleFunc(obj: object) {
    for (const property in obj) {
        const value = obj[property]; // This will result in a compilation error: attempting to index with type 'string' on type '{}'
    }
}

function anotherFunc(obj: { [propertyKey: string]: unknown }) {
    for (const key in obj) {
        const value = obj[key]; // This approach works without any issues :)
    }
}

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

We are unable to create a 'Worker' as Module scripts are not yet supported on DedicatedWorkers in Angular 8

Error An error has occurred in the following files: node_modules/typescript/lib/lib.dom.d.ts and node_modules/typescript/lib/lib.webworker.d.ts. Definitions of various identifiers conflict with those in other files, leading to modifier conflicts and dup ...

An unconventional approach to conducting runtime checks on Typescript objects

I've been working on a server application that receives input data in the form of JavaScript objects. My main task is to validate whether these data meet certain requirements, such as: having all required fields specified by an interface ensuring th ...

Tips for utilizing parent index as a parameter in a nested *ngFor loop

Having trouble passing my parent index to a nested ngFor in order to access an array of names like "name1, name2, etc." <ion-item *ngFor="let b of banca ; let i = index"> <ion-select> <ion-select-option *ngFor="let n ...

Leveraging the keyof keyword to access a specific property within a type

I have a variety of types that I need to work with. For example: type Type = { prop1: number; prop2: string; prop3: someOtherType } type Props = keyof Type I am aware that using an "indexed access type" allows me to extract the type of propN, ...

Struggling to Transform a Firebase Database Snapshot into an Array Using TypeScript

I've been following this tutorial on converting a firebase snapshot into an array for my ionic application. Here is the code I am using: You can find the code here. Here is my data structure in firebase: https://i.sstatic.net/xcYOv.png However, wh ...

Extending Interfaces Using Keys from an Array in Typescript

When dealing with a scenario where you want a pointfree omit, you can achieve this: type PlainObject<T> = {[key: string]: T} const omit = <K extends string>( name: K ) => <T, U extends PlainObject<T> & { [P in K]: T }>( ...

Ways to resolve the issue of npm being unable to globally install typescript

While trying to globally install TypeScript using npm sudo npm install -g typescript An error occurs during the installation process with the following message: ENOENT: no such file or directory, chmod '/usr/local/lib/node_modules/typescript/bin/ ...

Error occurred in child process while processing the request in TypeScript: Debug Failure encountered

I encountered the following error in TypeScript while running nwb serve-react-demo: Child process failed to handle the request: Error: Debug Failure. Expression is not true. at resolveNamesWithLocalCache (D:\Projects\react-techpulse-components& ...

The interactive Material UI Radio buttons are not responding to click events due to dynamic generation

Click here to see the demo in action: https://codesandbox.io/s/material-demo-9fwlz I expected this code to produce checkable radio elements, but it doesn't seem to be working correctly. Can anyone identify what might be causing the issue? This code s ...

Managing asynchronous data retrieval using rxjs

Within my service, I use an Observable to load data in the constructor. Later on, this data can be accessed using a getter, which should either return the data immediately if it's available or wait until the loading process is complete. Here is an exa ...

Leveraging vuex in conjunction with typescript allows for efficient management of state in namespace modules,

I am currently integrating vuex with typescript and namespaces module in my project. Within this setup, I have two distinct modules: "UserProfile" and "Trips". So far, everything is functioning smoothly within the confines of each module. However, I have ...

Set up your Typescript project to transpile code from ES6 to ES5 by utilizing Bable

Embarking on a new project, I am eager to implement the Async and Await capabilities recently introduced for TypeScript. Unfortunately, these features are currently only compatible with ES6. Is there a way to configure Visual Studio (2015 Update 1) to co ...

Exploring the potential of sharing a library folder in a monorepo with Nest.js and Angular.js

I am currently facing an issue while trying to share models and functions between two separate typescript projects - nest.js and angular.js. To initiate this process, I have set up boilerplate nest.js and angular.js projects in folders named api and ui res ...

Interactive form control for location details including country, state, district, and town

I am struggling with adding dynamic form controls on dropdown change. I have been able to add them, but encountered an error preventing me from retrieving the value in 'formName.value'. The specific error message states: "Error: There is no Form ...

What is the best way to utilize moment.js for adding days while excluding weekends?

I have a requirement to set a default follow-up date that is two days ahead of the current date. The existing code for this functionality is as follows: const Notify = moment().add(2, 'days').toDate(); Now, I need to modify this code to exclude ...

Unable to simulate a static method in Vitest - encountering an error stating "is not a function"

I am currently writing unit tests using the Vitest framework for my TypeScript and React application, but I have encountered an issue with mocking static methods. Below is a snippet of my code: export class Person { private age: number; constructor(p ...

Guide to establishing intricate conditions for TypeORM insertion

When attempting to insert data based on a specific condition, such as if shopId = "shopA", I want to include the shopdetail. In order to achieve this, I have implemented the following business logic, which is somewhat complex. Is there a more ef ...

Guide on transforming JSON data into a collection of custom objects using TypeScript

When working with raw data in TypeScript (originally a JSON file and imported using import * as raw_data from './json_file.json'): let raw_data: object = {"a": {"name": "Name a", "desc": "Description a ...

Is it possible for my commitment to consistently provide identical values, even when the data varies each time it is invoked?

Initially, the getCart method is invoked in b-navbar.component.ts: export class BNavbarComponent implements OnInit{ appUser: any; cart$ : Observable<ShoppingCart | null>; constructor(private auth : AuthService, private shoppingCartService : S ...

Validation in Express. The property 'validatePassword' is not found within the type 'Document'

Recently, I started working with express and node.js to create an authentication system without a frontend. I am utilizing typescript, passport, passport-local, and mongoose in my project. However, I encountered the following errors: TSError: ⨯ Unable t ...