Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element implicitly has an 'any' type because type '{}' has no index signature. [7017]

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?

like image 319
peter flanagan Avatar asked Dec 11 '18 08:12

peter flanagan


People also ask

How to fix “element implicitly has an ‘any’ type because type ‘window’?

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.

Does element implicitly have an'any'type?

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:

Is there an index signature with a parameter of type 'string'?

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]?

Can an object literal have an index signature derived from its properties?

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?).


1 Answers

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';
like image 184
rorschach Avatar answered Oct 04 '22 00:10

rorschach