Trying out TypeScript for a React project and I\'m stuck on this error:
Element implicitly has an \'any\' type because expression of type \'string\' can\'t b
This is what it worked for me. The tsconfig.json
has an option noImplicitAny
that it was set to true
, I just simply set it to false
and now I can access properties in objects using strings.
With out typescript
error
const formData = new FormData();
Object.keys(newCategory).map((k,i)=>{
var d =Object.values(newCategory)[i];
formData.append(k,d)
})
When using Object.keys
, the following works:
Object.keys(this)
.forEach(key => {
console.log(this[key as keyof MyClass]);
});
I made some small changes to Alex McKay's function/usage that I think make it a little easier to follow why it works and also adheres to the no-use-before-define rule.
First, define this function to use:
const getKeyValue = function<T extends object, U extends keyof T> (obj: T, key: U) { return obj[key] }
In the way I've written it, the generic for the function lists the object first, then the property on the object second (these can occur in any order, but if you specify U extends key of T
before T extends object
you break the no-use-before-define
rule, and also it just makes sense to have the object first and its' property second. Finally, I've used the more common function syntax instead of the arrow operators (=>
).
Anyways, with those modifications you can just use it like this:
interface User {
name: string;
age: number;
}
const user: User = {
name: "John Smith",
age: 20
};
getKeyValue(user, "name")
Which, again, I find to be a bit more readable.
When we do something like this obj[key] Typescript can't know for sure if that key exists in that object. What I did:
Object.entries(data).forEach(item => {
formData.append(item[0], item[1]);
});
Thanks to Alex Mckay I had a resolve for dynamic setting a props:
for(let prop in filter)
(state.filter as Record<string, any>)[prop] = filter[prop];