我有兩個這樣定義的介面:
export interface PostView{
postName: string;
postTime: Time;
message: string | null;
replies: { [P in AccountType]?: Reply[][] };
}
export interface Post{
postName: string;
postTime: Time;
message: string | null;
replies: { [P in AccountType]?: Reply[] };
}
您可以看到interface除了欄位之外,這兩個定義都是相同的replies。
現在,在一個.tsx檔案中,我得到一個PostView. 我想呼叫另一個需要Post物件的函式。此外,對于該replies欄位,我必須將空物件發送到函式。
這就是我目前的情況。
const postViewObject: any = props.myPostView;
postViewObject.replies= {};
const request: Post = postViewObject;
functionToBeCalled(request);
您可以看到我正在將PostView object分配給any我不想做的型別變數。然后我將replies欄位更新為空物件并將其轉換為Post物件。
有沒有更好的方法來撰寫這段代碼?
uj5u.com熱心網友回復:
您可以使用擴展運算子創建一個新的帖子物件:
const request: Post = {
...props.myPostView,
replies: {}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/492379.html
標籤:javascript 反应 打字稿 打字稿泛型
