我有這個函式可以根據 API 回應調整 React 組件的初始狀態。
export const getInitialStateByData = (initialData: TApiResponseData, fields: TFormFields) => {
for (const [key] of Object.entries(initialData)) {
if (!fields.includes(key)) {
delete initialData[key]
}
}
return initialData
}
我正面臨這個錯誤 Argument of type 'string' is not assignable to parameter of type 'TLocaleKey'.ts(2345) const key: string
我曾嘗試for (const [key]: [TLocaleKey] of Object.entries(initialData)) ...
與The left-hand side of a 'for...of' statement cannot use a type annotation.錯誤。
ts游樂場
鍵入密鑰的任何解決方案?提前致謝。
uj5u.com熱心網友回復:
for 的型別Object.entries如下(這就是為什么key輸入為string):
interface ObjectConstructor {
...
/**
* Returns an array of key/values of the enumerable properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
entries<T>(o: { [s: string]: T } | ArrayLike<T>): [string, T][];
/**
* Returns an array of key/values of the enumerable properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
entries(o: {}): [string, any][];
...
}
–參考
因此,我們將無法利用型別引數;元組entries回傳的第一項將始終是型別string。旁白:如果你很好奇,這就是為什么。
沒有辦法強制轉換在 for 回圈中宣告的變數(據我所知)。因此,您必須強制轉換陣列:
for (const [key] of (Object.entries(initialData) as [TLocaleKey, string][])) { ... }
–打字稿游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/328704.html
