Answer the question
In order to leave comments, you need to log in
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;
}, {});
}
Answer the question
In order to leave comments, you need to log in
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>);
}
CSSStyleDeclaration
.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question