[英]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.