So I accept that my google foo may just have been too weak to find the answer to this already so pointers to documentation would be happily accepted!
I am in the process of turning on strict type checking to an established typescript project.
One of the things I've come up against is how to best assign types to variables that cannot be correctly inferred.
For example, in this case the compiler throws an error because the type of obj is inferred as {} and cannot be indexed by string (please note this is a trivial example to illustrate the problem - I'm not looking for solutions to this specific case)
const arr = ['a', 'b', 'c', 'a'];
const obj = {};
arr.forEach(item => {
if (!obj[item]) {
obj[item] = 0;
}
obj[item] += 1;
}
What I would like to do here is to strictly type obj as a Record<string, number> but the compiler throws an error:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
No index signature with a parameter of type 'string' was found on type '{}'.ts(7053)
I've come across two ways to do this:
const obj: Record<string, number> = {};
or
const obj = {} as Record<string, number>;
Both result in the typescript engine resolving obj to the correct type, but I want to know if there is any difference between the two, and which is considered best practice (and why).