Answer the question
In order to leave comments, you need to log in
Reduce in TypeScript. How to correctly display the value of an object using the path to this value?
Good afternoon. Tell me how to correctly implement the function in TypeScript:
extractValue(row: object, path: string) {
return result = path.split('.')
.reduce((accumulator: object, currentValue: string) => accumulator[currentValue], row);
}
Answer the question
In order to leave comments, you need to log in
I'll add my solution. Thanks Alexei Yarkov for the tip. I will draw attention to the fact that the any type is not used .
interface IObjectItem {
[index: string]: IObjectItem | number | string;
}
extractValue(obj: IObjectItem, path: string): string | number {
const value = path.split('.').reduce((accumulator: IObjectItem | string | number, currentValue: string) => {
if (typeof accumulator === 'object' && accumulator[currentValue])
return accumulator[currentValue];
else
throw new Error(`Unexpected parameter "${currentValue}"`);
}, obj);
// Проверка типа получившегося значения
if (typeof value === 'string' || typeof value === 'number')
return value;
else
throw new Error('The final value must be string or number');
}
there is no normal built-in way. people have been asking for this for a long time, but to no avail: https://github.com/Microsoft/TypeScript/issues/12290
there are fierce perversions in the comments that people resort to to do something similar.
and in a simple way, to get one field, you can stupidly pass the desired generic type as a parameter and cast the received before returning. or pass a default value as a parameter in case there are no fields along the way, and deduce the return type from it.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question