键入如何在函数内部的递归函数中修复此问题



我正试图将我找到的JS函数转换为typescript,但我无法更正this参数:

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]*中。有什么建议可以解决这个问题吗?谢谢

您要搜索的是:https://www.typescriptlang.org/docs/handbook/2/functions.html#declaring-此功能

您可以将具有类型的this添加到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;
}

最新更新