[英]Nested Typescript Map Value Type
类似于嵌套打字稿映射类型,但嵌套在“值”端。
const mapObjectObject: Map<string, string | Map<string, string>> = new Map(Object.entries({
"a": "b",
"c": new Map(Object.entries({
"d": "e",
}))
})); // ✓
const mapObjectMap: Map<string, string | Map<string, string>> = new Map(Object.entries({
"a": "b",
"c": new Map([
["d", "e"]
])
})); // ✓
const mapMapObject: Map<string, string | Map<string, string>> = new Map([
["a", "b"],
["c", new Map(Object.entries({
"d": "e",
}))
]); // ✗
const mapMapMap: Map<string, string | Map<string, string>> = new Map([
["a", "b"],
["c", new Map([
["d", "e"]
])]
]); // ✗
为什么前两个有效,而后两个无效。 他们都犯了以下错误:
Overload 1 of 3, '(iterable: Iterable<readonly [string, string]>): Map<string, string>', gave the following error.
Argument of type '([string, string] | [string, Map<string, string>])[]' is not assignable to parameter of type 'Iterable<readonly [string, string]>'.
The types returned by '[Symbol.iterator]().next(...)' are incompatible between these types.
Type 'IteratorResult<[string, string] | [string, Map<string, string>], any>' is not assignable to type 'IteratorResult<readonly [string, string], any>'.
Type 'IteratorYieldResult<[string, string] | [string, Map<string, string>]>' is not assignable to type 'IteratorResult<readonly [string, string], any>'.
Type 'IteratorYieldResult<[string, string] | [string, Map<string, string>]>' is not assignable to type 'IteratorYieldResult<readonly [string, string]>'.
Type '[string, string] | [string, Map<string, string>]' is not assignable to type 'readonly [string, string]'.
Type '[string, Map<string, string>]' is not assignable to type 'readonly [string, string]'.
Types of property '1' are incompatible.
Type 'Map<string, string>' is not assignable to type 'string'.
Overload 2 of 3, '(entries?: readonly (readonly [string, string])[] | null | undefined): Map<string, string>', gave the following error.
Type 'Map<string, string>' is not assignable to type 'string'.(2769)
和
No overload matches this call.
Overload 1 of 3, '(iterable: Iterable<readonly [string, string]>): Map<string, string>', gave the following error.
Argument of type '([string, string] | [string, Map<string, string>])[]' is not assignable to parameter of type 'Iterable<readonly [string, string]>'.
Overload 2 of 3, '(entries?: readonly (readonly [string, string])[] | null | undefined): Map<string, string>', gave the following error.
Type 'Map<string, string>' is not assignable to type 'string'.(2769)
分别。 删除类型声明也无济于事。 推断类型也有同样的错误。
您应该向 TS 提供有关类型的提示:
const mapMapObject = new Map<string, string | Map<string, string>>([
["a", "b"],
["c", new Map(Object.entries({
"d": "e",
}))
]]);
const mapMapMap = new Map<string, string | Map<string, string>>([
["a", "b"],
["c", new Map([
["d", "e"]
])]
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.