[英]How get dynamic JSON generic type with TypeScript
我想从后端获取 JSON 类型的数据,但是 JSON 的类型必须是通用的。 它具有通用数量的值和通用键,我怎样才能正确编写 get 方法? 暂时我写这个:
getArticoliByDesc = (descrizione : string) => {
return this.httpClient.get<{
this.nomeChiave:
}[]>(`http://${this.server}:${this.port}/api/articoli/cerca/descrizione/${descrizione}`) //ALT + 0096 | ALT GR + '
}
我不知道我必须在<>
括号中写什么。
您可以将类型添加为 JSON。 typescript 中有一个类型。
示例代码
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 {
}
在你的情况下
getArticoliByDesc = (descrizione : string) => {
return this.httpClient.get<JSON>(`http://${this.server}:${this.port}/api/articoli/cerca/descrizione/${descrizione}`) //ALT + 0096 | ALT GR + '
}
但是仍然创建一个与您的 api 响应匹配的 Model class 将是最好的方法。 Even though api returns json, Angular http will convert it in to an object. 然后您可以通过添加 model 来概括
前任:
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 + '
}
如果您不知道响应类型并且您不关心输入,您可以执行以下操作:
const result = client.get<any>('URL');
如果您知道响应是 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');
如果您需要 typescript 来检查类型,那么您必须知道数据类型并为此创建类型。 例如:
type User = {
name: string;
email: string;
}
如果您期望响应是用户 object => { name, email }
const result = client.get<User>('URL');
如果您期望响应是用户数组 object => [ { name, email } ]
const result = client.get<User[]>('URL');
如果您期望响应是已知字符串变量的数组:
type KnownVariables = Array<'doctor' | 'programmer' | 'designer'>;
const result = client.get<KnownVariables>('URL');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.