Reputation: 16234
I want to write a function to substitute fields in a template with a series of values. The fields in the string template has the form {keyname}
. The code is as follows:
function replaceAll(template:string, values:object) {
Object.keys(values).map((e) => {
const key = new RegExp("{" + e + "}", "g");
template = template.replace(key, values[e]); //xxx
});
return template;
}
let result = replaceAll("the {q} brown {f}...", { q: "quick", f: "fox"});
Unfortunately this code won't compile. At values[e]
at xxx, it gives:
Element implicitly has an 'any' type because type '{}' has no index signature.
(parameter) values: object
What does the error message mean and how can I fix it?
Upvotes: 3
Views: 8327
Reputation: 7130
You can use the following type: { [key: string]: string }
, naturally changing string
to whatever may be passed in as the key and value, respectively.
You're receiving the error message because when you access the value of the object, it doesn't know what type it should be, and is therefore implicitly any. You can, of course, still have a value that is explicitly any, but you'll still need to use something like the example I gave.
Upvotes: 7