Converting a TypeScript array into a generic array of a specific class

I am attempting to convert a JSON source array with all string values into another array of typed objects, but I keep encountering errors. How can I correct this code properly? Thank you.

Error 1: There is an issue with converting type '({ Id: string; CompanyName: string; ...)[]' to type 'Dest'. The two types do not have sufficient overlap, which may result in an error. If this conversion was intentional, consider first converting the expression to 'unknown'.

Error 2: In '../grid-second.component.ts:12', there is a TypeScript error (TS2740) indicating that the type 'Dest' is missing essential properties present in type 'any[]': length, pop, push, concat, and more. 12 public gridData: any[] = destination;

export const source = [{
    'Id': 'ALFKI',
    'CompanyName': 'Alfreds Futterkiste',
    'DOB': '01/31/2000' // optional field
}, {
    'Id': 'ANATR',
    'CompanyName': 'Ana Bokov Emparedados y helados',
}, 

export class Dest{
    public Id: string = "";
    public CompanyName: string = "";
    public DOB?: Date
}

export const destination = <Dest>source;  // Error 1.

Within the Angular component:

public gridData: any[] = destination;  // Error 2.

https://i.sstatic.net/UuHza.png

Answer №1

To create instances of your class, you can add a constructor and utilize the map function:

class Dest {
    public Id: string = "";
    public CompanyName: string = "";
    public DOB?: Date;

    constructor(id: string, companyName: string, dob: string | undefined) {
        this.Id = id;
        this.CompanyName = companyName;

        // TODO: not seeing Timezone in source objects.
        this.DOB = dob ? new Date(dob): undefined;
    }
}

const destination: Dest[] = source.map(x => new Dest(x.Id, x.CompanyName, x.DOB));

If you prefer to work without creating a class or using new, Interfaces or Types can be used. In any case, conversion from string DOB to Date DOB is necessary:

interface IDest {
    Id: string;
    CompanyName: string;
    DOB?: Date;
}

const destination: IDest[] = source.map(x => ({...x, DOB: x.DOB ? new Date(x.DOB) : undefined}));

Playground: click

Answer №2

When I need to accomplish this task, my go-to method is using Object.assign(). Typically, I implement this within an RXJS Map operation while fetching data from a server.

Alternatively, you can also employ the array map function like so:

newData = data.map(item => Object.assign(new Target(), item));

In your specific case, where you're hardcoding an array, it might be more efficient to directly create the values as part of initializing the array instead of manipulating them later:

export const data = [Object.assign(new Target, {
    'Id': 'ALFKI',
    'CompanyName': 'Alfreds Futterkiste',
    'DOB': '01/31/2000' // potentially not available
}), Object.assign(new Target, {
    'Id': 'ANATR',
    'CompanyName': 'Ana Bokov Emparedados y helados',
})
]

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

Attempting to invoke a promise within a function yields an error message stating that it lacks call signatures

Recently, I came across this interesting class: export class ExponentialBackoffUtils { public static retry(promise: Promise<any>, maxRetries: number, onRetry?: Function) { function waitFor(milliseconds: number) { return new Pr ...

Encoding a JSON representation of an HTML list where all children are displayed at each parent item

Here is the structured list that I am currently working with: function convert( name_ref ) { name_ref = name_ref + " > ol > li"; var mylist = []; $(name_ref).each(function () { if ($(this).find('> ol > li').length){ myl ...

typescript optimizing initial load time

When importing the npm package typescript, it typically takes around 0.3 seconds. Is this considered an acceptable load time? Are there any steps that can be taken to optimize performance? The code snippet in index.js demonstrates the process: import &apo ...

bundle.js encountered a TypeError when attempting to read a property that was undefined, specifically while trying to access the PriceIndexationDataControlStandard

In the midst of developing a React component using the Microsoft PCF Framework, I encountered a perplexing error seemingly out of the blue. While making changes in TypeScript without even executing any build commands, the rendering of my component suddenly ...

Error with Array type encountered in Typescript's find method

I am encountering an issue with code that looks like this: type X = { test: number; x: number; }[]; type Y = { test: number; y: number; }[]; type Z = { test: number; z: number; }[]; export const testFunc = (arg: X | Y | Z) => { return a ...

What is the best way to download a file with a specific name using Angular and TypeScript?

Greetings! Below is a snippet of code from my Angular component: this.messageHistoryService.getMessageHistoriesCSV1(msgHistoryRequest).subscribe( (data) => { console.log(data.messageHistoryBytes); let file = new Blob( [data.messageHistoryBytes ...

Jhipster entity authentication

For my latest project with JHipster, I decided to incorporate Angular 2 and MongoDB. One of the entities I created is a 'doctor' with attributes such as name (string), login (string), password (string), and specialty (string). Now I want to enabl ...

Creating a ref in React with TypeScript to access the state of a child component

Is there a way to access the state of a child component within the parent component without using handlers in the child or lifting the state up in the parent? How can I utilize refs in React with TypeScript to createRef and retrieve the child's state ...

What is the process of integrating socket.io with Angular and how can we establish persistent communication using a socket service in Angular?

Just diving into Angular and trying to retrieve continuous dynamic data from a socket server. The server side seems to be set up correctly, but I'm having trouble actually receiving the data from the socket server. ...

Using TypeScript to set an HTMLElement in a web page

Currently in the process of transitioning my old JavaScript code to TypeScript. One of the components I have is a Table Of Contents JSX component that helps me navigate easily to specific headings. I had a function that calculated the total offset needed ...

Multiple subscriptions without having to recalculate the shared components

const ex = ajax.getJSON('https://httpbin.org/get?a=24'); ex.pipe(pluck('args')).subscribe(x => console.log('Arguments: ', x)); ex.pipe(pluck('headers')).subscribe(x => console.log('Response Headers: ' ...

What could be causing my function to not successfully retrieve elements based on their text content?

A function called matchTagAndText is designed to take two arguments: a selector and text, checking if any matched elements contain the specified text. The function code is as follows: function matchTagAndText(sel, txt) { var elements = document.queryS ...

Structuring an Angular 2 Project

Embarking on a new project in Angular2, I find myself pondering the optimal structure for an Angular2 application. Imagine I have various pages such as home, auto-galleries, nearest-galleries, brands, cars, and selected-car. The navigation sequence could b ...

pick out particular values from an array

I have a question that may seem basic to some, but I'm curious about how to select specific elements from an array. In this case, I have an array with 100 elements: var cubes = [element1, element2, element3 ...] and I want to select elements 25-35. ...

Passing a variable from one Bash file to a JQ command in a separate Bash script

Objective I am attempting to pass a variable from one Bash file into a JQ command in another Bash file. Situation In a JSON file, there are two empty values that I need to fill with: An HTML file A variable located in a different Bash file (file-b.sh) ...

Click on an element in Angular to toggle it

A function in my codebase is responsible for toggling a specific section within a div element. Currently, there are a total of 3 sections available in the app. The functionality is implemented in the app.component.ts file: show = false; toggle() { ...

Creating a new object in Typescript with properties that are a subset of another object's properties, determined by an array

The title I wrote might be a bit complicated, so let me clarify my intentions below. Imagine I have a specific type for a document that contains some data: type Doc<TData extends {}> = { data: TData; } In addition, there is a function where I can ...

Steps for launching a stackblitz project

Apologies for the novice question. As a beginner in Angular (and StackBlitz), I have created a StackBlitz project to seek assistance on an Angular topic (reactive forms). However, I am unable to run it. Can anyone guide me on how to do so? Thank you. ...

Unable to display label in form for Angular 2/4 FormControl within a FormGroup

I'm having trouble understanding how to: Use console.log to display a specific value Show a value in a label on an HTML page Display a value in an input text field Below is my TypeScript component with a new FormGroup and FormControls. this.tracke ...

How can I iterate through a JavaScript object in a recursive manner?

I am endeavoring to design a function that will generate an output like the following when given an object: <div> reason : ok status : 0 AiStatistics : null CurrentSeasonArenaStatistics : null <div> Player <div> CampaignProgr ...