[英]typescript - cast json to an interface
我有一個像這樣的界面:
export default interface IProject extends{
Id?:number;
name?:string;
description?:string;
}
當我從服務器獲取數據時,我的json文件包含更多類似的屬性:
{
id,
name,
description,
url,
startDate,
finishDate
}
但我只需要ID,名稱和說明字段。 我嘗試了這個:
response.data.map((p: any) => p as IProject);
但是對象包含不必要的數據,例如url,startdate和finishDate,如何正確映射它們? 我知道我們可以這樣映射它們:
response.data.map((p: any) => {
return {id:p.id,name:p.name,description:p.description}
});
但是還有其他更好的方法嗎?
我建議您做您正在做的事情,但同時還要為服務器響應添加一些類型。 這樣,您將獲得一些映射功能的智能感知。
interface IProject {
id?: number;
name?: string;
description?: string;
}
interface IProjectResponse {
id?: number;
name?: string;
description?: string;
url?: string;
startDate?: string;
finishDate?: string;
}
const mapResponse = (response: IProjectResponse[]) => response.data.map((p) => ({
id: p.id,
name:p.name,
description: p.description,
}));
const response = await fetch(/* .. */);
const data = await response.json();
const projects: IProject[] = mapResponse(data);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.