我正在嘗試將找到的 JS 函式轉換為打字稿,但我無法處理更正此引數:
getProperty(object: {}, key: string) {
function iter(a: string) {
// @ts-ignore
const item = this ? this[a] : a;
// @ts-ignore
if (this && a === key) {
return result.push(item);
}
if (Array.isArray(item)) {
return item.forEach(iter);
}
if (item !== null && typeof item === 'object') {
return Object.keys(item).forEach(iter, item);
}
}
const result: string[] = [];
Object.keys(object).forEach(iter, object);
return result;
}
我嘗試了我在網上找到的系結和其他建議,但問題是該功能停止作業。為了使它作業,我保持 ts 忽略行。我首先嘗試將 iter 函式轉換為箭頭但停止正常作業,然后問題仍然存在于代碼 * this[a]* 中。有什么建議可以解決這個問題嗎?謝謝
uj5u.com熱心網友回復:
您正在搜索的是:https ://www.typescriptlang.org/docs/handbook/2/functions.html#declaring-this-in-a-function
您可以將this帶有型別的 a 添加到 iter 函式。
對于您的示例,這可能如下所示:
function getProperty(object: {}, key: string) {
function iter(this: Record<string, any>, a: string) {
const item = this ? this[a] : a;
if (this && a === key) {
return result.push(item);
}
if (Array.isArray(item)) {
return item.forEach(iter);
}
if (item !== null && typeof item === 'object') {
return Object.keys(item).forEach(iter, item);
}
}
const result: string[] = [];
Object.keys(object).forEach(iter, object);
return result;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/507822.html
下一篇:計算物件內嵌套陣列的最高級別
