export interface IHtmlProperties {
website?: string
favIcon?: string;
}
function getHtml(htmlTemplate: string, properties: IHtmlProperties) {
const options : IHtmlProperties = {
website: properties.website,
favIcon: properties.favIcon
};
let html = htmlTemplate;
Object.keys(options).forEach(function(key) {
html = html.replace('{{' + key + '}}', options[key]);//<==== Error
});
return html;
}
Accessing options[key] throwing error as below
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'IHtmlProperties'.
No index signature with a parameter of type 'string' was found on type 'IHtmlProperties'.
If IHtmlProperties doesn't have optional params, I can easily write options[key as keyof IHtmlProperties].
But here IHtmlProperties has some optional parameters. Any idea how to solve this?
Update with fix The earlier problem is because of replace having the value of undefined. So checking for value validity fixed the error
let html = htmlTemplate;
(Object.keys(options)).forEach(function(key) {
const value = options[key as keyof IHtmlProperties];
if(value) {
html = html.replace('{{' + key + '}}', value);
}
});
return html;
The accepted answer helped me in figuring it out! Thanks for that!