I am converting a JS file to TS, in my react native project but have stumbled accross this issue that I can’t resolve where the value['flag']
is showing the following error,
‘value’ is of type ‘unknown’.ts(18046). Any idea on how to solve this will be much appreciated.
The code block is the following:
for (const [key, value] of Object.entries(orderedCities)) {
if (
key.startsWith(userInput.toLowerCase()) &&
userInput != '' &&
value !== typeof undefined
) {
const inputObject = {city: '', flag: ''};
inputObject.city = key;
inputObject.flag = value['flag'];
creationArray.push(inputObject);
setElementArray(creationArray);
}
}
I tried declaring a type in the const [key, value] but this triggers a different error, I added the value !== typeof undefined
but this has not changed the error showen.
2
Answers
Use
for..in
when you wan to iterate over object.You are expecting
value
to be an object with a property{ flag: string }
. Right now the entirevalue
has typeunknown
. It’s not even know that it is anobject
.This means that something is wrong with the type of your
orderedCities
variable. That is, the problem is somewhere higher up in your code.Perhaps you initialized an empty dictionary without declaring its type. I can reproduce your
'value' is of type 'unknown'
error if I createorderedCities
as:I can get rid of the error by creating
orderedCities
with a proper type:You will want to remove your attempted solution
&& value !== typeof undefined
. This doesn’t make sense astypeof undefined
is astring
. It will give you an error of its own once you have a proper type onorderedCities
.Corrected code:
TS Playground Link