V
V
Vladimir2019-08-05 10:44:13
typescript
Vladimir, 2019-08-05 10:44:13

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);
}

How to correctly specify the return type of a function (string | number | undefined)?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir, 2019-08-06
@z3d01n

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');
}

The function itself consists of 2 parts: the first one gets the value based on the given path, the second one checks the type of the output value.

F
forspamonly2, 2019-08-05
@forspamonly2

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 question

Ask a Question

731 491 924 answers to any question