我正在嘗試訪問型別為物件中的鍵FilterType
這是界面 -
export interface FilterType {
name?: string[];
status?: string[];
brand?: string[];
categoryAndColour?: {
[category: string]: string[];
};
rating?: string[];
}
這是物件 -
const newState: FilterType = { ...state };
我正在嘗試使用一個函式來洗掉 newState 中的所有鍵,但是每當我嘗試通過物件映射或映射到 for..in 時,我都會不斷收到類似的錯誤。
我目前正在嘗試這個 -
for (var key in newState){
delete newState[key];
}
return newState;
但我得到了錯誤Element implicitly has an 'any' type because expression of type 'string' can't be used to index type
和No index signature with a parameter of type 'string' was found on type
我該如何解決這個問題?
uj5u.com熱心網友回復:
由于您正在嘗試創建一個新的空狀態,只需將 定義newState為一個新物件:
const newState: FilterType = {};
如果您仍然想洗掉所有鍵,請在(TS playground)key中使用之前定義型別:for..in
let key: keyof FilterType;
for (key in newState){
delete newState[key];
}
uj5u.com熱心網友回復:
你為什么不把一個空物件回傳到這個狀態呢?
uj5u.com熱心網友回復:
嘗試這個:
Object.keys(newState).forEach((key) => delete newState[key]);
現在,如果你運行:
console.log(newState)
預期的輸出將是一個空物件:
{ }
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/454260.html
標籤:javascript 打字稿 类型 javascript 对象 反应打字稿
上一篇:匯編:為什么堆疊上有空記憶體?
下一篇:是否可以動態生成下拉項?
