I am trying to convert a JS function i found to typescript but i am unable to handle correct the this argument:
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;
}
I tried the bind and other suggestions that i found in the web but the problem is that the function stops working. To make it working i keep the ts ignore lines. I first tried to convert the iter function into arrow but stops working properly and then the problem remains in the code * this[a]*. Any suggestions to fix this? Thank you
CodePudding user response:
What you are searching for is this: https://www.typescriptlang.org/docs/handbook/2/functions.html#declaring-this-in-a-function
You can add a this
with a type to the iter function.
For your example this could look like:
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;
}