My search skills may have failed me in finding the answer to this question, so any guidance towards relevant documentation would be appreciated!
I am currently working on enabling strict type checking in an existing TypeScript project.
One issue I've encountered is how to assign types to variables that cannot be inferred correctly.
For instance, the compiler raises an error in this scenario where the type of obj
is inferred as {}
and cannot be indexed by string
. (Note: This is a simplified example for illustration purposes only)
const arr = ['a', 'b', 'c', 'a'];
const obj = {};
arr.forEach(item => {
if (!obj[item]) {
obj[item] = 0;
}
obj[item] += 1;
}
In this case, I aim to strictly type obj
as a Record<string, number>
, but encounter an error from the compiler:
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 identified two methods to address this:
const obj: Record<string, number> = {};
or
const obj = {} as Record<string, number>;
Both approaches lead to the correct typing of obj
by TypeScript, but I'm curious about any distinctions between the two and which one is considered best practice (along with reasoning).