gpt4 book ai didi

TypeScript 错误编译 map

转载 作者:搜寻专家 更新时间:2023-10-30 20:57:29 25 4
gpt4 key购买 nike

let a : any;
let m = new Map<any, any>(Object.keys(a).map(prop => ([prop.x, prop.y])));

esnext目标产生错误

file: 'file:///c%3A/GIT/MainLine/members/src/tasks/list/decTest2.ts' severity: 'Error' message: 'Argument of type 'any[][]' is not assignable to parameter of type 'Iterable<[any, any]>'. Types of property '[Symbol.iterator]' are incompatible. Type '() => IterableIterator' is not assignable to type '() => Iterator<[any, any]>'. Type 'IterableIterator' is not assignable to type 'Iterator<[any, any]>'. Types of property 'next' are incompatible. Type '(value?: any) => IteratorResult' is not assignable to type '(value?: any) => IteratorResult<[any, any]>'. Type 'IteratorResult' is not assignable to type 'IteratorResult<[any, any]>'. Type 'any[]' is not assignable to type '[any, any]'. Property '0' is missing in type 'any[]'.' at: '4,27' source: 'ts'

这很奇怪,因为

let m2 = new Map<any, any>([[1, 2], [2, 3], ['a', 'b']])

编译正常。我需要在第一个示例中添加什么才能编译?

请注意,我确实知道

let m2 = new Map<any, any>(<any>[[1, 2], [2, 3], ["a", 'b']])

也会修复它,但我想了解为什么会出错,看看是否有更合适的修复。

最佳答案

问题是 TypeScript 不确定您的数组在该上下文中是元组还是普通数组。类型参数推理尝试仅将其参数用作推理站点。

因此,在调用 map 时, 它不会从 new Map<any, any>(...) 的参数类型中得出推论) 到 map 的返回类型.

TypeScript 2.4 正在制作 some changes在这个方向,和your specific scenario was brought up .关于问题本身的讨论和进展可以tracked here .

作为解决方法,您可以编写一个显式的返回类型

(prop): [any, any] => [prop.x, prop.y]

或者你可以给map显式类型参数

Object.keys(a).map<[any, any]>(...)

请注意,无论哪种情况,TypeScript 都会捕获 x 的错误和 y不是 string 上的有效属性

关于TypeScript 错误编译 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44181762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com