I'm trying to figure out how to access the array field of an object in TypeScript. It seems like the type 'unknown' is required to have a '[Symbol.iterator]()' method that returns an iterator

I'm currently tackling an issue with my helper function that updates a form field based on the fieldname. For example, if it's the name field, then form.name will be updated. If it's user[0].name, then the name at index 0 of form.users will be updated. However, I've encountered an error which can be seen in the simplified code snippet below:

const example: Record<string, unknown> = {
    'a': 'haha',
    'b': [1,2,3],
};
const str = 'b.haha';
const tokens: string[] = str.split(".");
if (typeof example[tokens[0]][Symbol.iterator] === 'function') {
    const c = [...example[tokens[0]];
}

playground

I'm struggling to resolve this error: Type 'unknown' must have a 'Symbol.iterator' method that returns an iterator. Thanks

Answer №1

The issue lies in setting the second generic argument of Record to unknown. It may be more suitable for your case to use any instead:

const example: Record<string, any> = { // <- change is in this line
    'a': 'haha',
    'b': [1,2,3],
};
const str = 'b.haha';
const tokens: string[] = str.split(".");

if (typeof example[tokens[0]][Symbol.iterator] === 'function') {
    const c = [...example[tokens[0]];
    console.log(c);
}

Check Playground

In my opinion, the main difference between unknown and any is that you must actively cast variables of type unknown, while with any you can do anything. This makes unknown a bit safer as it detects errors at compile time when manipulating a variable of type unknown without knowing its type.

Personally, I suggest keeping unknown and leveraging TypeScript's type guards to automatically cast c to any[]:

const example: Record<string, unknown> = {
    'a': 'haha',
    'b': [1,2,3],
};
const str = 'b.haha';
const tokens: string[] = str.split(".");

const value = example[tokens[0]];

if (Array.isArray(value)) {
    const c = [...value];
    console.log(c);
}

Play around on Playground

For further understanding, consider reading about unknown versus any.

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

Guide to locating the recursive function in Node.js runtime

As a beginner in the world of node and angular development, I have encountered a major issue - "FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory". Is there anyone who can help me identify the function ...

Incorporate a CSS class name with a TypeScript property in Angular version 7

Struggling with something seemingly simple... All I need is for my span tag to take on a class called "store" from a variable in my .ts file: <span [ngClass]="{'flag-icon': true, 'my_property_in_TS': true}"></span> I&apos ...

What is the best way to add a repository in Nest.js using dependency injection?

I am encountering an issue while working with NestJS and TypeORM. I am trying to call the get user API, but I keep receiving the following error message: TypeError: this.userRepository.findByIsMember is not a function. It seems like this error is occurring ...

My Angular Router is creating duplicate instances of my route components

I have captured screenshots of the application: https://ibb.co/NmnSPNr and https://ibb.co/C0nwG4D info.component.ts / The Info component is a child component of the Item component, displayed when a specific link is routed to. export class InfoComponent imp ...

ngif directive does not function properly when subscribe is utilized in ngOnInit

this is the unique component code import { Component, OnInit } from '@angular/core'; import { Subscription } from 'rxjs'; //import { Item } from '../item/item.model'; import { CartItem } from './cart-item.model'; imp ...

`Why TypeScript in React may throw an error when using a setter`

As I work on building a small todo app in TypeScript with React, I encountered an issue when attempting to add a new todo item to my list. It seems like the problem may lie in how I am using the setter function and that I need to incorporate Dispatch and s ...

Unit testing in Angular 2+ involves testing a directive that has been provided with an injected window object

Currently, I am faced with the challenge of creating a test for a directive that requires a window object to be passed into its constructor. This is the code snippet for the directive: import { Directive, ElementRef, Input, OnChanges, OnDestroy, OnInit ...

Match and populate objects from the array with corresponding items

Currently, I have an array and object containing items, and my goal is to check each item in the array to see if its path matches any of the object names. If a match is found, I push it into that object's array. While this part is working fine, I am ...

Steps for selectively targeting and updating a group of properties in a TypeScript class

Is there a way to consolidate this code into one function that can handle all the tasks below? I'm adding more text here to meet the requirements and hoping for a solution. Thank you! TypeScript is an amazing language that differs slightly from JavaS ...

What is the process for searching my database and retrieving all user records?

I've been working on testing an API that is supposed to return all user documents from my Mongo DB. However, I keep running into the issue of receiving an empty result every time I test it. I've been struggling to pinpoint where exactly in my cod ...

Incorporating TypeScript basics into the if statement post compiling

As I delve into the Angular2 Quickstart, I stumbled upon a peculiar issue within app.component.js after compiling app.component.ts using tsc (version 1.8.2): if (d = decorators[i]) I am unable to pinpoint where I may have gone wrong in configuring the qu ...

Angular: Real-time monitoring of changes in the attribute value of a modal dialog and applying or removing a class to the element

I cannot seem to figure out a solution for the following issue: I have two sibling div elements. The second one contains a button that triggers a modal dialog with a dark overlay. However, in my case, the first div appears on top of the modal dialog due to ...

Resolving search box setup problem in PrimeNG dataView

I am working on integrating p-dataView with Angular 5 but encountering an error Cannot read property 'split' of undefined at DataView.filter Despite checking the documentation, I have been unable to find a solution to this issue. It seems lik ...

Defining assertions with specified type criteria

Looking to do something special in TypeScript with a class called Foo. I want to create a static array named bar using const assertion, where the values are restricted to the keys of Foo. This array will serve as the type for the function func while also a ...

Strategies for extracting information from the database

I have a pre-existing database that I'm trying to retrieve data from. However, whenever I run a test query, it always returns an empty value: { "users": [] } What could be causing this issue? entity: import {Entity, PrimaryGeneratedColumn, Col ...

Exploring the Power of Node.JS in Asynchronous Communication

Hey there, I'm not here to talk about async/await or asynchronous programming - I've got that covered. What I really want to know is if it's possible to do something specific within a Node.js Express service. The Situation I've built ...

Infinite Loop Issue in Angular2 RC5 when using the templateUrl

Encountering an issue with Angular2 RC5 that seems to be causing an infinite loop problem. The app.component, which is bootstrapped by the app.module, appears quite simple: @Component({ selector: 'my-app', template: `TEST` }) export cl ...

Node.js does not allow the extension of the Promise object due to the absence of a base constructor with the required number of type

I'm trying to enhance the Promise object using this code snippet: class MyPromise extends Promise { constructor(executor) { super((resolve, reject) => { return executor(resolve, reject); }); } } But I keep encou ...

How can I configure React Router V6 to include multiple :id parameters in a Route path, with some being optional?

Currently, I am utilizing react-router@6 and have a Route that was previously used in V5. The route is for vehicles and always requires one parameter (:id = vehicle id), but it also has an optional second parameter (:date = string in DD-MM-YYYY format): &l ...

Next.js is failing to infer types from getServerSideProps to NextPage

It seems like the data type specified in getServerSideProps is not being correctly passed to the page. Here is the defined model: export type TypeUser = { _id?: Types.ObjectId; name: string; email: string; image: string; emailVerified: null; p ...