As a newcomer to TypeScript, I am in the process of migrating some of my custom components/plugins to TS.
One of the challenges I'm facing is setting object properties dynamically when the property name is a variable.
I would greatly appreciate a best-practice solution or pattern to help me with this.
Here is my code:
interface Options {
repeat: boolean;
speed: number;
}
class MyPlugIn {
$el:HTMLElement;
options:Options;
constructor ($el:HTMLElement, options:Partial<Options> = {}) {
this.$el = $el;
// Set default options, override with provided ones
this.options = {
repeat: true,
speed: 0.5,
...options
};
// Set options from eponymous data-* attributes
for (const option in this.options) {
if (this.$el.dataset[option] !== undefined) {
let value: any = this.$el.dataset[option];
// Cast numeric strings to numbers
value = isNaN(value) ? value : +value;
// Cast 'true' and 'false' strings to booleans
value = (value === 'true') ? true : ((value === 'false') ? false : value)
// Attempt 1:
// ERROR: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Options'.
this.options[option] = value;
~~~~~~~~~~~~~~~~~~~~
// Attempt 2 (with assertions):
// ERROR (left-hand): Type 'string' is not assignable to type 'never'
// ERROR (right-hand): Type 'option' cannot be used as an index type.
this.options[option as keyof Options] = value as typeof this.options[option];
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~
}
}
/* ... */
}
/* ... */
}
Appreciate any help!