Muhammad Ali
Muhammad Ali

Reputation: 47

How to construct instance of class using json object array

I'm trying construct the class's object from the array.

import searchData from '../somepath/data.json';

And the data.json file have the following data.

[
  {
    "name": "London"
  },
  {
    "name": "Paris",
  }
]

Then I'm looping it using the forEach.

searchData.forEach((obj: OneClass) => {
});

Here is the class

export class OneClass{
  readonly name: string;
}

It is not working well, I'm getting some kind of type error.

But when I just change the type of searchData to any then it works perfectly,

const searchData: any = [
    {
        'name': 'a'
    }, 
    {
        'name': 'b'
    }, 
    ];

Note: some code are missing due to privacy restriction, so just trying to understand how the construct the object of typescript class using array objects.

Edited:

The json data was importing using the following method.

import searchData from '../somepath/data.json';

Upvotes: 1

Views: 152

Answers (3)

geoM
geoM

Reputation: 497

You can either annotate your array explicitly ..

// tell TS that the variable holds an array of objects 
// shaped like instances of OneClass
const searchData: OneClass[] = [
  {
    name: 'a'
  }, 
  {
    name: 'b'
  }, 
];

or use a so-called const assertion.

const myConstArr = [
    {
      name: 'bar'
    } as const 
    // the `as const` tells TS that the value of `name` is not going to change 
    // (that it is a "string literal type" and not just of type `string`)
]

Have a look at the concept of Type Narrowing.

Here is a playground for you to check it out.

Upvotes: 1

Aaron Ross
Aaron Ross

Reputation: 141

If what you are doing is trying to create an instance of the class for each item in your array of objects, you need to map and call the constructor:

interface SearchDatum {
 name: string;
}

const searchData: SearchDatum[] = [
  {
    'name': 'a'
  }, 
  {
    'name': 'b'
  }, 
];

class OneClass {
  readonly name: string;

  constructor({ name }: SearchDatum) {
    this.name = name;
  }
}

const classInstances: OneClass[] = searchData.map((datum) => new OneClass(datum));

Here is a Typescript playground link

Upvotes: 0

Thomas Sablik
Thomas Sablik

Reputation: 16449

You should type your array

const searchData: OneClass[] = [
{
    'name': 'a'
}, 
{
    'name': 'b'
}, 
];

Upvotes: 0

Related Questions