对象中键的索引签名
index signature of a key in an object
我有以下打字稿代码
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 是上下文类型
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
s 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', [])
我有以下打字稿代码
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 是上下文类型
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
s 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', [])