1

I'm trying to simply index into a dictionary using typescript, here is a naive example that fails on lines 9 and 10. I get the errors Element implicitly has an 'any' type because type object has no index signature. and Element implicitly has an 'any' type because type {} has no index signature.

1 var configs = { 2 'stuff': { 3 'stuff1': 12, 4 'stuff2': 13, 5 } 6 }; 7 var locked = new Object(); 8 for (var config in configs) { 9 configs[config]['stuff1'] += 1; 10 locked[config] = true; 11 } 

Other SO answers offer advice like making locked and configs into a custom Dict type (type Dict = { [key: string]: object };). This also did not work and provided the same error.

1 Answer 1

2

3 ways to solve it:

Use explicit any instead of implicit:

var configs: any = { 'stuff': { 'stuff1': 12, 'stuff2': 13, } }; var locked: any = {}; for (var config in configs) { configs[config].stuff1 += 1; locked[config] = true; } 

You can also disable noImplicitAny in your tsconfig.

Using any explicitly or implicitly in your own code kind of defeats the purpose of typescript and I would not recommend it.

The best solution would be to define a type that is as strict as possible for your situation. For your example it could be like this:

interface Config { stuff1: number; stuff2: number; } var configs: { [key: string]: Config } = { stuff: { stuff1: 12, stuff2: 13, } }; var locked: { [key: string]: boolean } = {}; for (var config in configs) { configs[config].stuff1 += 1; locked[config] = true; } 

But you will probably have to adjust config to your actual situation.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! Can you provide some intuition as to why you have to cast it to any or use that other workaround?
nothing here is a workaround. TypeScript is configured to complain if it does not recoqnize a specific type for an object noImplicitAny. The entire point of using typescript is to have type safety. If typescript can't ensure that, it gives you an error. That happens here with your config object, because no type is specified. You can specify it's type as 'any' and with that you tell typescript: 'I know what im doing don't check here', but that is not recommend. The approach from my 2nd example uses typescript as intended by having a safe type defining the config

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.