Using Typescript: ForOf Iteration with Unknown Value Types

My journey began with a quick peek at this particular inquiry. However, the approach discussed there utilized custom typing. I am currently iterating over object entries using a for-of loop. Here's a snippet of the values I'm dealing with below. During this process, I discovered that in order to access functions on a certain type of object, checking the instance is necessary. This logic applies to everything except strings. It seems like I have to utilize String instead of string when applying the instanceof operator, yet this leads to errors due to the fact that String is not compatible with string. As a result, I find myself pondering upon alternative solutions and wondering if there exists a more efficient way to tackle this issue.

    const value = 
    {
        EnableDataMining: 1, EnableReassembly: 0, Alarm: [1,2,3],
        AllowQuery: 1, AllowDrilldown: 1, MessageType: ["sms", "msm","carrier pidgeon"],
        AllowBypass: 0, Bybass: (1) [false, "01/01/1970"]
    }

    for(const [k, v] of Object.entries(value))
    {
        th.headers = td.headers = th.textContent = key;
                    
        if(v instanceof Array) v.map(i => td.textContent = i);
        if(v instanceof Number) td.textContent = v.toString();
        if(v instanceof String) td.textContent = v;

        console.log(k, v);
    }

Answer №1

One effective method to determine if the variable v is a string or number is by utilizing the typeof operator:

if (typeof v === "number") {
    td.textContent = v.toString();
}
if (typeof v === "string") {
    td.textContent = v;
}

It's important to remember that you should enclose "string" and "number" in quotes when comparing them with the result of typeof v.

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

Certain Array properties cause Array methods to generate errors

I am working with an Array prop in my component's props that is defined like this props: { datasetsList: { type: Array as PropType<Array<ParallelDataset>>, required: false } }, Within the setup() method of my component, I have ...

The Intersection of Material-UI, TypeScript, and Powerful Autocomplete Features

In my TypeScript project, I'm attempting to develop a Material-UI AutoComplete component that retrieves the input value based on an object's property name -> obj[key] However, when using the prop getOptionLabel, I encountered the following er ...

Caught up: TypeScript not catching errors inside Promises

Currently, I am in the process of developing a SPFx WebPart using TypeScript. Within my code, there is a function dedicated to retrieving a team based on its name (the get() method also returns a promise): public getTeamChannelByName(teamId: string, cha ...

Building TypeScript Model Classes

Greetings! As a newcomer to TypeScript with a background in both C# and JavaScript, I am on a quest to create class models resembling those found in C#. Here's my attempt so far: export class DonutChartModel { dimension: number; innerRadius: ...

What is the best location for storing test utilities in Next.js applications?

My Next.js (12.x) React (18.x) project includes Jest (28.x) for testing. While my tests in files like __tests__/Product.test.tsx work smoothly, I encountered an issue when trying to reuse some utils across tests: __tests__/util/my-test-helper.ts export fu ...

Eslint for Typescript in Vue is throwing an error with a message "Unexpected token, expecting ','. Make sure to

Whenever I attempted to utilize vue's type assertion, I kept encountering this eslint error. To illustrate, consider the following snippet: data: function () { return { sellerIdToListings: {} as any, // 'as' Unexpected to ...

Using Typescript in the browser with Babel and Webpack: Step-by-Step Guide

I've been exploring the use of Typescript in my browser with a specific architecture: Typescript in browser architecture However, I'm facing an issue with the import/export functionality when running this command: tsc && babel build-ts -d lib && ...

The database migration encounters an issue: The module 'typeorm' cannot be located

When I run the following commands: ❯ node --version v16.19.0 ❯ yarn --version 3.5.0 I am attempting to launch this project: https://github.com/felipebelinassi/typescript-graphql-boilerplate However, when I execute: yarn db:migrate which runs the c ...

Is there a way to execute Typescript tests using JasmineKarma within a TFS Build Process?

My current setup involves a web application using Angular 1.5 with bower/npm/gulp written in Typescript for our build process. The back end is a c# .net WebApi2, and both are built and deployed on TFS2015. Integrating my c# NUnit tests into the build proce ...

How to retrieve a Typescript variable within an ngIf conditional statement in Angular

How can I access a TypeScript variable inside an ngIf statement? TS: public data: string; HTML: <td> <div *ngIf="data === 'BALL' ; else noplay" >{{ play }}</div> <ng-template #noplay> {{ gotohome ...

Issue with Angular 8: click event is not triggering when using ngFor directive to iterate through arrays of objects

Update: The original post has been modified to omit implementation details and complexity. I am facing an issue with an ngFor loop that invokes a method on a service. The method returns an array which is then iterated over by the for loop. The click even ...

Leveraging the power of the Async pipe within an Angular TypeScript file

Using the async pipe in HTML involves utilizing the syntax "Products$ | async as products". But can we also access these same products in the TypeScript file? Is this possible? ...

Using ngModel instead of value to bind a custom Angular directive for currency input

Currently, I am using a specialized mat-input-currency format directive to automatically convert my field inputs into currency. You can find the npm repository here. However, the directive binds the element data to [value] of the input, and I require it t ...

Error encountered while attempting to generate migration in TypeORM entity

In my project, I have a simple entity named Picture.ts which contains the following: const { Entity, PrimaryGeneratedColumn, Column } = require("typeorm"); @Entity() export class Picture { @PrimaryGeneratedColumn() ...

Use Enums instead of conditions in Typescript

Consider the code snippet below, which is a function that generates a CSS class based on the value of toCheck: const computeSomething = (toCheck: string) => { return clsx('flex', { 'flex-start': toCheck === 'FIRST', ...

Is there a way to restrict an array to only accept distinct string literals?

export interface IGUser { biography: string; id: string; ig_id: string; followers_count: number; follows_count: number; media_count: number; name: string; profile_picture_url: string; shopping_product_tag_eligibility: boolean; username: ...

Creating a new list by grouping elements from an existing list

I have successfully received data from my API in the following format: [ {grade: "Grade A", id: 1, ifsGrade: "A1XX", ifsType: "01XX", points: 22, type: "Type_1"}, {grade: "Grade B", id: 2, ifsGrade: &quo ...

Next.js (TypeScript) - Error: Property 'req' is not recognized on the type 'GetServerSideProps'

Currently, I am tackling a challenge involving the utilization of next-auth and attempting to access the session from within getServerSideProps. However, in order to achieve this, it is essential for me to provide the context request and context response ...

Typescript tutorial: Implementing a 'lambda function call' for external method

The Issue Just recently diving into Typescript, I discovered that lambda functions are utilized to adjust the value of this. However, I find myself stuck on how to pass my view model's this into a function that calls another method that hasn't b ...

Encountering build errors in .xproj file when working with Type Script in ASP.Net Core

I recently started working on a new ASP.Net Core project and decided to integrate Angular 2 and Type Script by following a blog post tutorial. However, upon adding a Type Script file to my project, I encountered several build errors from the xproj file. h ...