0

我有以下打字稿代码

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'] = []

其中 ctx 属于 Context 类型

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

我收到以下错误

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'] = []

我不确定如何将索引签名添加到 Map 类型

4

1 回答 1

2

Maps 不像您预期​​的那样支持索引语法。.has(key)可以使用、.get(key)和等方法访问它们.set(key, value)

errors[ctx.env].set('something', [])
于 2019-03-30T08:48:21.137 回答