Defining typed objects in Typescript

After reading the string, an array of objects is created for various operations. However, upon returning the final array, I encounter a problem - the year needs to be a number instead of a string.

for (let i = 1; i < allFileLines.length; i++) {
                    const data = allFileLines[i].split("|");
                    if (data.length === newheaders.length) {
                        const tarry: Icface = {
                            title: null as string,
                            id: null as string,
                            year: null as number,
                        };
                        for (let j = 0; j < newheaders.length; j++) {
                            tarry[newheaders[j]] = data[j];
                        }
                        if (typeof tarry[2] === "number") {
                            Log.trace("number");
                        }
                        // tslint:disable-next-line:no-console
                        // console.log(lines);
                        // Log.trace(JSON.parse(JSON.stringify(tarry)));
                        lines.push(tarry);
                    }
                }

The interface looks like this:

export interface Icface {
    title: string;
    id: string;
    year: number;
    [key: string]: string | number;
}

So even though the year value after processing is returned as "2018", it should actually be 2018. It's perplexing how I'm able to work with the string representation of the year using operators like "<" and "===". Any ideas?

Answer №1

The Icface interface provided below allows the attribute year to be of type string or number.

export interface Icface {
  title: string;
  id: string;
  year: number;
 [key: string]: string | number; // it enables 'year' to have a value of string or number
}

Kindly consider modifying the for loop from

for (let j = 0; j < newheaders.length; j++)
to

for (let j = 0; j < newheaders.length; j++) {
  if (newheaders[j] === 'year') {
    tarry.year = +data[j];
  else {
    tarry[newheaders[j]] = data[j];
  }
}

Answer №2

After separating a string into an array of strings, experiment with this code snippet:

const tarry: Icface = {
  title: data[0],
  id: data[1],
  year: parseInt(data[2]),
};

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

Issue with Android Cordova: Unable to assign value to property 'text' because it is set to null

While attempting to run cordova prepare on my project, I encountered the following error : (node:11384) UnhandledPromiseRejectionWarning: TypeError: Cannot set property 'text' of null at updateProjectAccordingTo (C:\Users\Utilisateur&b ...

What steps should I take to update my Vue 2 components for use in Vue 3?

I am considering using my Vue 2 components in a new Vue 3 project, is this possible? For example, I currently have Vue 2 components for "FAQ" and "About Us". Can I incorporate these components into a Vue 3 project by creating routes to use them? I initiall ...

Combining two kebab-case CSS classes within a React component

import React from 'react'; import styles from './stylesheet.moudle.css' <div className={styles['first-style']} {styles['second-style']}> some content </div> What is the correct way to include styles[&ap ...

What could be causing the data to be displaying as undefined when using AJAX

My issue involves making an ajax call and passing an array with data. However, when I attempt to debug the code in the console, it shows that the data is undefined. What could be causing this? ...

The disappearance of a JavaScript click event within an update panel

I have a situation where I am using an asp.net updatepanel that contains three dropdowns and a submit button. Using javascript, I bind a "click" event to the submit button to capture the values of the dropdowns. However, when I select a new value from a dr ...

Passing a JSON file name as an argument to a command line in Node.js

When I run app.js using the command node app.js, it will execute const inputData = require('./input.json'); Now, my question is - can I pass the file name as an argument to const inputData = require('./file.json'); directly from the co ...

Having trouble with a peculiar for_of loop issue in Node.js: struggling to iterate correctly

Currently immersed in a Python project, I find myself in need of retrieving data from a Node.js API. Despite my limited knowledge of Node.js, I attempted to write some code for this purpose. Here is the code snippet: const SneaksAPI = require('sneaks ...

The integration of Angular PWA is posing challenges with Angular Ivy

_ _ ____ _ ___ / \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _| / △ \ | '_ \ / _` | | | | |/ _` | '__| | | | | | | / ___ \| | | | (_| | |_| | | (_| | | | ...

Tips on displaying dynamic content on a single page with AngularJS 1.6

Just getting started with Angular and looking for a way to display dynamic content from a JSON file using AngularJS 1.6? Here's an example to help you out. News.json { "Articles": [ { "Title": "News 1", ...

issues arising from an array in need of a function to retrieve data from Firestore

My current task involves developing a method that can read an array of elements (objects) from firestore: I've set up a service to fetch the data from firestore, starting with retrieving an array of document references var data = snapshot.get(&apos ...

What is the best way to iterate over an indexed attribute in PHP?

Here is my ajax code snippet: $.ajax({ type: "POST", url: "bee_sesi_edit.php", data: 'serv_ruang='+ serv_ruangx +'&who='+names +'&sesi_d1='+ sesi_d1 +&apos ...

Is it possible to adjust the size and placement of a shadowbox/greybox window to appear within a specific div element on the webpage?

Is it feasible to resize and relocate a greybox or shadowbox window for presentation within a specific div element? In the process of designing a WordPress site template, I've incorporated the default calendar feature. However, upon clicking a date o ...

In what way can you retrieve scope values (when testing) from an Angular controller implemented in TypeScript?

When working with Angular controllers in TypeScript, you have the option to define your controller in a way that accepts the $scope as an input parameter: class TestCtrl { constructor($scope:ng.IScopeService) { $scope.myData = "Information"; ...

Object in motion from left to right

For my game, I am planning to introduce obstacles that move from left to right across the <div id="outline"></div>. I have implemented a solution using setInterval(){...} and .animate(), which works well initially. However, after some time, it ...

What is the process for configuring a headless implementation of three.js on a node server, similar to the babylon.js-NulEngine setup?

My current project involves the development of a multiplayer three.js fps game, with client-side prediction in the browser. For the server-side implementation, I am utilizing Node.js Express.js and Socket.io for handling authoritative functions such as col ...

Why can't I omit <someUnion, oneInterface> in TypeScript?

Kindly review this simple example: interface A { a: number; } interface B { b: number; } interface C { c: number; } type ABC = A | B | C; type omitA = Omit<ABC, A>; https://i.sstatic.net/5Mun4.png Unfortunately, I am unable to exclude an i ...

What is the process for activating namespacing on a VueX module that has been imported?

I am currently utilizing a helper file to import VueX modules: const requireModule = require.context('.', false, /\.store\.js$/) const modules = {} requireModule.keys().forEach(filename => { const moduleName = filename ...

Close pop-up upon successful AJAX response in ASP.NET MVC

I have a modal in my view that allows me to create a new record in the database. The view for this functionality is contained within a partial view. Below is the code for the view: <script src="~/Scripts/jquery-3.1.1.js"></script> To han ...

Strategies for capturing the click event on a particular mesh within a group

Currently, I am working with a set of circle geometry elements that are arranged on the vertices of an icosahedron element. I am looking to trigger a click event on each individual circle element using jQuery. Can you provide guidance on how to implement j ...

Unable to display content on the ejs file

Currently, I have been diving into the world of node.js and exploring how to manipulate data by writing and reading from JSON files. It has been an interesting journey so far; however, I encountered a hiccup. Specifically, when attempting to post new data ...