我正在嘗試為我的 api 回應定義靈活的型別,但無法弄清楚如何使用 TypeScript 4.5.4 進行型別轉換。我想決議回應并獲取稍后將在代碼中使用的型別,回應型別僅用于在決議之前正確鍵入。
TS 游樂場(編輯:固定 ID)
// this and ReviewResponse are specific to reviews
export type Review = {
id: number;
name: string;
rating: number;
review: string;
};
export type ReviewResponse = ResponseType<Review>;
// this is a general type placed elsewhere
export type ResponseType<Item> = {
id: number;
attributes: {
[key: string]: Item
}
}
// parser function to run after fetching the data
function parseResponse(data: ReviewResponse[]): Review[] {
return data.map((item) => {
return {
id: item.id,
...item.attributes,
};
});
}
函式parseResponse有一個錯誤可見下面。為什么 TS 不明白 Item 是 Review 型別,我錯過了什么?:
Type '{ id: number; }[]' is not assignable to type 'Review[]'.
Type '{ id: number; }' is missing the following properties from type 'Review': name, rating, review (2322)
uj5u.com熱心網友回復:
如果attributes包含具有該物件的其他屬性的物件,則它的型別應該是Item,或者更具體地說Omit<Item, 'id'>。
export type ResponseType<Item> = {
id: string;
attributes: Omit<Item, 'id'>
}
// parser function to run after fetching the data
function parseResponse(data: ReviewResponse[]): Review[] {
return data.map((item) => {
return {
id: item.id,
...item.attributes,
};
});
}
游樂場鏈接
[key: string]: Item意味著屬性可以Item在不同的鍵下具有多個屬性。所以它可能是這樣的{ "A": { /*attributes of Review*/ }, "B": { /*attributes of Review*/ } }
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/414460.html
標籤:
