Can the type of an object be dynamically assigned in Typescript?

I keep encountering the eslint warning "@typescript-eslint/no-unsafe-assignment". This warning occurs when I am trying to extract specific keys and values from a variable that can be assigned objects of different types, with approximately 10 possible classes.

// var **key** can be any property of object1 and depending on which property 
// the result will be an object that is of multiple different types
Object.keys(object1).forEach((key) => {

    const object2 = object1[key]; // depending on key this can be of type class A, B, C, D and so on

    Object.getOwnPropertyNames(object2).forEach((property) => {
        // ESLINT error because linter does not know the type of object2
        // which could be multiple classes depending on key
        const var1 = object2[property]

I attempted a solution but it didn't work as expected. How can I handle this scenario where I am uncertain about the type of my object because I am iterating through them dynamically.

// properties with **class type** values
const objectTypes = {
    first: A,
    second: B,
    third: C,
    fourth: D,
}
....
....
// Then based on the property that is the same value as the key to get object2
// I get the correct type from my objectTypes
const var1Type = objectTypes[key];
const var1 = (object2 as var1Type)[property];

Answer №1

The value returned by Object.keys(obj) or Object.getOwnPropertyNames(obj) is of type string[] and not Array<keyof typeof obj>. This discrepancy is due to the fact that an object can be typed more strictly than its actual content. For instance:

type MyType = {
    foo: string,
};

// Type inference
const myObj = {
    foo: 'test',
    bar: 1,
};

// Specified type
const myTypedObj: MyType = myObj;

const keys = Object.keys(myTypedObj); // Although `myTypedObj` is of type `MyType`, the keys are ['foo', 'bar'] instead of just ['foo']
console.log(keys);

TypeScript Playground

If you need to iterate through an object's keys using Object.keys, it's advisable to filter them based on the keys known to your specified type. This way, TypeScript can accurately determine the type of the property being accessed.

Based on the linting error, it appears that TypeScript is inferring the property type as any, which poses a risk as type checks are not performed on values with the any type.

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

Remove httpOnly cookies in Express

Can browser cookies with the attribute HttpOnly:true be deleted? Here is a snippet of my login endpoint: async login(@Ip() ipAddress, @Request() req, @Res() res: Response) { const auth = await this.basicAuthService.login(req.user, ipAddress); ...

Using Tailwind classes as a prop functions correctly, however, it does not work when directly applied

Here's a component snippet I'm working on: export const TextInput = ({ label, wrapperClassName = "", inputClassName = "", labelClassName = "", placeholder = "", ...props }: InputProps & Fiel ...

Dynamically apply classes in Angular using ngClass

Help needed with setting a class dynamically. Any guidance is appreciated. Below is the class in my SCSS file: .form-validation.invalid { border: 2px solid red } In my ts file, there's a variable named isEmailValid. When this variable is set to ...

Alias in webpack for Typescript modules

I'm facing an issue where I need to assign an alias for 'Hammer' in my code. I've already included the necessary paths in my tsconfig file as shown below: { "compilerOptions": { "declaration": true, "noImplicitAny": false , ...

How can we set up the Typescript Compiler to recognize typings and modules effectively?

I have been working on a TypeScript project with the following structure: <work folder>/Scripts/ (project root) +-- App +--- subfolder1 +--- subfolder2 +-- typings After openi ...

Tips on adding an item to an array with React hooks and TypeScript

I'm a beginner with a simple question, so please bear with me. I'm trying to understand how to add an Object to the state array when a form is submitted. Thank you for your help! interface newList { name: string; } const ListAdder = () => { ...

Enhance your Three.js development with TypeScript autocomplete

In my project using Node.js, Typescript, and Three.js, I have set up the commonjs syntax for module imports in my tsconfig.json file like this: { "compilerOptions": { "module": "commonjs" } } I installed Three.js via NPM and created a typescript ...

Cannot establish a connection with Socket.IO

I've encountered an issue with establishing a connection to Socket.IO in my node server. Although the server starts successfully with Socket.IO, I am not seeing any console logs when trying to connect to Socket. this.server.listen(this.port, () => ...

Did not adhere to regulations

Currently, I am in the process of developing a React app. However, when I attempt to initiate my project using npm start in the terminal, I encounter an error message on the browser. https://i.stack.imgur.com/wej1W.jpg Furthermore, I also receive an erro ...

Having trouble getting code hints to function properly with the official TypeScript plugin on Sublime Text 3

I am experiencing issues with getting code hinting to work using the official TypeScript plugin for Sublime Text 3 on Mac OSX 10.10.5 with Sublime 3. Despite installing it in the packages directory, I am unable to see any code hints. In accordance with th ...

Having trouble entering text into a React input field

Encountering a puzzling issue with a simple form featuring an input field that inexplicably won't respond to keyboard typing. Initially, suspicions pointed towards potential conflicts with the onChange or value props causing the input to be read-only. ...

Discovering the number of items that have been filtered in isotope-layout using React and Typescript

Currently, I am utilizing the isotope-layout library within a React (Typescript) project. Although I have successfully implemented filtering on my page, I am unsure of how to retrieve the count of the filtered items. Upon loading the page, Isotope is init ...

How can you retrieve the keys of an object that conforms to an interface?

In the following demonstration, we have two objects - KEYS and KEYS2. When importing KEYS in index.ts, autocomplete suggestions are available for K1 and K2 because KEYS does not adhere to an interface. On the other hand, with KEYS2, autocomplete is not pr ...

Creating an extended class with mandatory properties

In order to streamline code sharing between two classes that overlap, I decided to create a new class called Common. For one of the subclasses, I needed all the properties from the Common class to be required. My initial thought was to utilize the Require ...

Options for importing TypeScript in WebStorm

Using WebStorm for auto-importing TypeScript classes has been a great help to tidy up my code and make it more organized. However, I have noticed that the imports are always formatted in a single line like this: import { Component, EventEmitter, Input, O ...

Automatically assign the "Restricted" cursor to disabled fields within a dynamic form

Is there a method in Angular 6/7 that allows the cursor to change to "Not Allowed" when hovering over a disabled field in a reactive form? I prefer not to use CSS for this cursor change. Is there a way to achieve this through Angular alone? Currently, th ...

Utilize Page.evaluate() to send multiple arguments

I am facing an issue with the Playwright-TS code below. I need to pass the email id dynamically to the tester method and have it inside page.evaluate, but using email:emailId in the code throws an undefined error. apiData = { name: faker.name.firstNa ...

Encountered an error while loading resource: net::ERR_CONNECTION_REFUSED in Nodejs

I am currently working on a form in my angular 6 app with nodejs, utilizing nodemailer for sending emails. Unfortunately, I am encountering an error that reads: Failed to load resource: net::ERR_CONNECTION_REFUSED : :3000/contact/send:1 Below is the form ...

Tips for integrating the react-financial-charts library into your React and JavaScript project

While exploring the react-financial-charts library, I discovered that it is written in TypeScript (TS). Despite my lack of expertise in TypeScript, I am interested in using this library in my React+JS project due to its active contributions. However, I hav ...

SonarQube alerting you to "Eliminate this unnecessary casting"

Can someone help me understand why SonarQube is flagging this error and suggest a resolution? The unnecessary cast should be removed. Promise.all([ this.customerViewCmr4tProvider.getData(activeNumber), this.customerBillManagementProvider.getData(ind ...