I am using typescript and am seeing the following error
[ts] Element implicitly has an 'any' type because type '{}' has no index signature. [7017]
const store = {};
setItem: jest.fn((key, value) => {
store[key] = value.toString();
})
I can fix it by setting the store to any like so
const store: any = {};
but I would like to type it, but can't figure out how to do this. Can anyone help?
To fix the "Element implicitly has an ‘any’ type because type ‘Window’ has no index signature?" error in TypeScript, we can add dynamic properties into the Window interface. index signature so that we can add and use any property in window without compiler errors.
I'm not sure if this is the same issue, but I'm getting a similar Error: TS7017: Element implicitly has an 'any' type because type 'iAbilityModifiers' has no index signature. Here's a simplified example:
No index signature with a parameter of type 'string' was found on type '{ red: null; green: null; blue: null; }'. I tried looking everywhere on TypeScript docs, but how the heck am I suppose to interfacethis so it can accept color[e]?
Interesting point -- a fresh object literal type certainly could have an index signature derived from its properties. Not sure how common this pattern is in practice, though (do you really want to allocate a new object every time this function gets called?).
Well, what kind of type do you want it to have? If it's just a simple key-value pair then this will suffice:
type Dict = { [key: string]: string };
const store: Dict = {};
store['foo'] = 'bar';
Edit (June of 2019)
Typescript also has a built-in type called Record
which is meant for this use case - as long as your type is not supposed to have any predefined keys!
const store: Record<string, string> = {};
store.foo = 'bar';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With