Nick Ginanto
Nick Ginanto

Reputation: 32130

index signature of a key in an object

i have the following typescript code

type MapOfErrors = Map<string, Error[]>
interface GatheredErrors {
  'dev': MapOfErrors
  'prod': MapOfErrors
  [key: string]: MapOfErrors
}

const errors: GatheredErrors = {
  dev: new Map<string, Array<Error>>(),
  prod: new Map<string, Array<Error>>()

}

 errors[ctx.env]['something'] = []

where ctx is of Type Context

interface Context {
  token: string
  env: "dev" | "prod"
}

I get the following error

src/index.ts:136:5 - error TS7017: Element implicitly has an 'any' type because type 'Map<string, Error[]>' has no index signature.

136     errors[ctx.env]['something'] = []

I'm not sure on how to add the index signature to the Map type

Upvotes: 0

Views: 135

Answers (1)

Maps don't support the index syntax like you expected they would. They are accessed using methods such as .has(key), .get(key), and .set(key, value):

errors[ctx.env].set('something', [])

Upvotes: 2

Related Questions