The attribute specified is not present on the element within the array

I'm attempting to create an array that includes an object with initialized properties and a number.

Yet, I encounter this error message:

The error states: 'Property 'foo' does not exist on type 'number | IObj'. The property 'foo' is not available on type 'number.'

interface IObj {
    [k: string]: string
}

function test(fields: string[]){
    const foo: IObj = {}
    fields.forEach((x) => foo[x] = 'baz')
    return [foo, 1]   
}
const [foo, x] = test(['foo'])
foo.foo

Is there a solution to resolve this issue? Thank you.

Answer №1

With array literals in typescript, the default behavior is for types to be inferred, resulting in each element being of type IObj | number. This means that the specific information regarding the first element being of type IObj and the second being a number gets lost during destructuring.

In the recently released version 3.4, you can use as const to instruct the compiler to infer a readonly tuple (return [foo, 1] as const)

Alternatively, you can provide an explicit type annotation to specify that you intend to have a tuple:

interface IObj {
    [k: string]: string
}

function test(fields: string[]) : [IObj, number]{
    const foo: IObj = {}
    fields.forEach((x) => foo[x] = 'baz')
    return [foo, 1]  
}
const [foo, x] = test(['foo'])
foo.foo

If you plan to use constants for the fields parameter, consider using a more type-safe approach like this:

function test<K extends string>(fields: K[]) : [Record<K, string>, number]{
    const foo = {} as Record<K, string>
    fields.forEach((x) => foo[x] = 'baz')
    return [foo, 1]  
}
const [foo, x] = test(['foo'])
foo.foo //ok
foo.foo2 // err

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

A guide on validating an array of literals by leveraging the power of class-validator and class-transformer through the methods plainToInstance or plainTo

I am struggling with my validation not working properly when I use plainToInstance to convert literals to classes. Although the transformation appears to be successful since I get Array(3) [Foo, Foo, Foo] after using plainToInstance(), the validation does ...

What is the process for triggering property decorators during runtime?

Wondering about dynamically invoking a property decorator at runtime. If we take a look at the code snippet below: function PropertyDecorator( target: Object, // The prototype of the class propertyKey: string | symbol // The name of th ...

A method to simultaneously retrieve all emitted values from multiple EventEmitters in Angular 7

I am facing a scenario where I have a parent component that consists of multiple child components. Each child component may differ from the others, creating a diverse structure within the parent component. Here's an example: ...

Is it possible to retrieve the signature for every method within a class?

Let's consider a scenario where we have a class defined as follows: class Actions { static FooAction = 'foo' as const; someAction1() { return { type: Actions.FooAction, payload: {a: 1, b:2} }} static BarAction = &apos ...

A guide on how to follow a specific item in an Angular 2 store

I have integrated ngrx store into my Angular2 application. The store reducer contains two objects as shown below: export function loadSuccessNamesAction(state: StoreData, action: loadSuccessNamesAction): StoreData { const namesDataState = Object.assi ...

When using EcmaScript imports with the 'node16' or 'nodenext' module resolution, it is important to include explicit file extensions in relative import paths. For example, did you intend to use './*.js'?

Within my package.json file, I have set "type": "module" and utilize SWC for compiling TypeScript code. For imports, I utilize import Example from './example'. In addition, I use the following script: "start": " ...

Tips for sending a function with arguments in a React application using TypeScript

Is there a way to streamline passing a handleClick function to the son component so that it does not need to be repeated? The code in question is as follows: Mother Component: const Mother = () => { const [selectedOption, setSelectedOption] = useSt ...

Unable to initialize a public variable due to issues with Ionic Storage retrieval

I am currently facing an issue where I am trying to assign a token stored in the Ionic storage module to a public variable. However, when I attempt to set the token and then access it from another function, I encounter an undefined error. Here is the code ...

filtering an array based on a specific property will result in the original array remaining

Working on filtering an array of objects based on a certain property using the following code snippet: if (payment == Payment.CREDIT_CARD) { this.currenies.filter((currency: Currency) => currency.isFromEurope === true); console.log(this.currencies) ...

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 ...

Fixing Typescript assignment error: "Error parsing module"

Trying to assign an object to the variable initialState, where the type of selectedActivity is Activity | undefined. After using the Nullish Coalescing operator (??), the type of emptyActivity becomes Activity. However, upon execution of this line, an err ...

Setting text in a datetime picker with ngx-mat-datetime-picker in an Angular application is a straightforward process

I've been utilizing the ngx-mat-datetime-picker library from angular-material-components to enable datetime selection. It's functioning effectively, but I'm searching for a way to insert text preceding the hour and minute inputs, such as &ap ...

Building a multi-platform desktop application using Angular and Electron integrated with ngx

Having developed an Angular application, there is now a need for a desktop version as well. Electron was used to run the application, and everything is functioning as intended. However, an issue arises with localization. In the electron application, only ...

Guide for Showing Data from Json Mapper in Angular 5

As a newcomer to Angular5 with TypeScript, I am trying to figure out how to display data from my JSON. I have an API that was created using Java. I have created a JSON Mapper in my Angular code like this : The JSON generated from my Java application looks ...

Verify that the Angular service has been properly initialized

I am currently testing my Angular service using Karma-Jasmine and I need to verify that the loadApp function is called after the service has been initialized. What would be the most effective approach for testing this? import { Injectable, NgZone } from ...

What is the solution for resolving the JavaScript runtime error '0x800a1391 - 'require' is undefined'?

As a C# developer with limited web experience, I am currently diving into learning Typescript. However, I seem to be facing a roadblock in the form of an error message. 0x800a1391 - JavaScript runtime error: 'require' is undefined To provide so ...

Intellisense for dispatch types in Redux Toolkit

After following the documentation for redux toolkit with typescript, I implemented my own useDispatch hook as shown below export const useAppDispatch = () => useDispatch<AppDispatch>() and used it in components like this const dispatch = useAppDi ...

Using a class as an interface in TypeScript is a common practice when a constructor is

Consider a scenario where I have a class structured like this: class MyClass { a: string } Now, let's say I create a variable with the following definition: let obj: MyClass = { a: 2 } An error will be triggered in Typescript because 2 is not ...

What is the method for reaching a service in a different feature module?

Currently, I am utilizing Angular 2/4 and have organized my code into feature modules. For instance, I have a Building Module and a Client Module. https://i.stack.imgur.com/LvmkU.png The same structure applies to my Client Feature Module as well. Now, i ...

Using TypeScript to pass objects to an arrow function

Issue at Hand: How do I successfully transfer an object from a parent component to a child component that is derived from the same interface? I am currently facing difficulties in rendering a list of tasks by looping through a list of task objects. The ma ...