R
R
Rustam2020-06-10 23:24:21
typescript
Rustam, 2020-06-10 23:24:21

Typescript. How to collect an object from an array of strings?

I'm trying to make a method that will take an array of strings, and produce an object with the keys of these strings at the output, and take the values ​​from another object.
Specifically in my case:
You need to pass an array of strings to the method, which are the names of styles
, for example: The method will run through the array and form an object, I do this using reduce. I tried to do something like this:
['width', 'fontSize', 'fontStyle', ...]

getStyles(styles: Array<keyof CSSStyleDeclaration>): Record<keyof CSSStyleDeclaration, string> {
    return styles.reduce((res, style) => {
      res[style] = this.$nativeElement.style[style];
      return res;
    }, {});
  }

Error pointing to res[style] // Element implicitly has an 'any' type because expression of type 'number | "textAlign ...
Also, I did not specify the return value correctly, I just don't know how to do it right.

How can I implement this? It is desirable that when calling the method I know what it will return.

I do not use any

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2020-06-10
Demonov @Demonov

In fact, in order to have full-fledged typing, you need something like this:

getStyles<T extends keyof CSSStyleDeclaration>(styles: readonly T[]) {
  return styles.reduce((res, style) => {
    res[style] = this.$nativeElement.style[style];
    return res;
  }, {} as Pick<CSSStyleDeclaration, T>);
}

Sandbox .
The difference with Dmitry 's solution is that the type of the resulting object will contain only the received keys, and not all possible ones in CSSStyleDeclaration.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question