Home > OS >  How get dynamic JSON generic type with TypeScript
How get dynamic JSON generic type with TypeScript

Time:09-12

I want to get JSON type of data from backend, but the type of JSON must be generic. It has a generic number of values and generic keys, how can I correctly write the get method? For the moment I write this:

getArticoliByDesc = (descrizione : string) => {
    return this.httpClient.get<{
      this.nomeChiave:
    }[]>(`http://${this.server}:${this.port}/api/articoli/cerca/descrizione/${descrizione}`) //ALT   0096 | ALT GR   '
  }

I don't know what I must write in <> brackets.

CodePudding user response:

You can add the type as JSON. there is a type in typescript for that.

sample code

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-array-json-dates',
  templateUrl: './array-json-dates.component.html',
  styleUrls: ['./array-json-dates.component.scss']
})
export class ArrayJsonDatesComponent implements OnInit {
  jsonObject: JSON;

  arrayObj: any = [
    {
      id: 1,
      name: "john",
      lastModified: '2011-01-01 02:00:00'
    },
    {
      id: 2,
      name: "Franc",
      lastModified: '2001-01-01 02:00:00'
    },
    {
      id: 3,
      name: "Andrew",
      lastModified: '2021-01-01 02:00:00'
    },
    {
      id: 11,
      name: "Mark",
      lastModified: '2020-01-01 02:00:00'
    },
    {
      id: 12,
      name: "Eric",
      lastModified: '2020-02-01 02:00:00'
    },
    {
      id: 8,
      name: "Tony",
      lastModified: '1990-01-01 02:00:00'
    }
  ]

  constructor() {
    this.jsonObject = <JSON>this.arrayObj;

  }

  ngOnInit(): void {

  
}

In your case

   getArticoliByDesc = (descrizione : string) => {
    return this.httpClient.get<JSON>(`http://${this.server}:${this.port}/api/articoli/cerca/descrizione/${descrizione}`) //ALT   0096 | ALT GR   '
  }

But still creating a Model class which matched your api response would be the best way to do this. Even though api returns json, Angular http will convert it in to an object. Which you can then generalize by adding your model

Ex:

export class ApiModel{
   property1: string;
   property2: string;
   property3: string;
} 

   getArticoliByDesc = (descrizione : string) => {
    return this.httpClient.get<ApiModel>(`http://${this.server}:${this.port}/api/articoli/cerca/descrizione/${descrizione}`) //ALT   0096 | ALT GR   '
  }

CodePudding user response:

If you don't know the response type and you don't care about the typing, you can do:

const result = client.get<any>('URL');

If you know the response is an object but you don't know the properties, you dan do:

const result = client.get<{ [key: string]: unknown }>('URL');

// Or create an alias.
type Data = { [key: string]: unknown };

const result = client.get<Data>('URL');

// Or if you expect an array.
const result = client.get<Data[]>('URL');

If you need typescript to check the type, then you have to know the data type and create a typing for that. For example:

type User = {
  name: string;
  email: string;
}

If you expect the response is a User object => { name, email }

const result = client.get<User>('URL');

If you expect the response is an array of User object => [ { name, email } ]

const result = client.get<User[]>('URL');

If you expect the response is an array of known string variables:

type KnownVariables = Array<'doctor' | 'programmer' | 'designer'>;

const result = client.get<KnownVariables>('URL');
  • Related