简体   繁体   English

如何使用 TypeScript 获取动态 JSON 泛型类型

[英]How get dynamic JSON generic type with TypeScript

I want to get JSON type of data from backend, but the type of JSON must be generic.我想从后端获取 JSON 类型的数据,但是 JSON 的类型必须是通用的。 It has a generic number of values and generic keys, how can I correctly write the get method?它具有通用数量的值和通用键,我怎样才能正确编写 get 方法? 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.我不知道我必须在<>括号中写什么。

You can add the type as JSON.您可以将类型添加为 JSON。 there is a type in typescript for that. typescript 中有一个类型。

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.但是仍然创建一个与您的 api 响应匹配的 Model class 将是最好的方法。 Even though api returns json, Angular http will convert it in to an object. Even though api returns json, Angular http will convert it in to an object. Which you can then generalize by adding your model然后您可以通过添加 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 + '
  }

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:如果您知道响应是 object 但您不知道属性,您可以这样做:

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.如果您需要 typescript 来检查类型,那么您必须知道数据类型并为此创建类型。 For example:例如:

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

If you expect the response is a User object => { name, email }如果您期望响应是用户 object => { name, email }

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

If you expect the response is an array of User object => [ { name, email } ]如果您期望响应是用户数组 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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM