![](/img/trans.png)
[英]TypeScript error Element implicitly has an 'any' type because expression of type 'any' can't be used to index type
[英]use reduce in typescript, Error "element implicitly has an 'any' type because expression of type can't be used to index type '{}'"
我得到错误:
元素隐式具有 'any' 类型,因为类型 'POST_TYPE' 的表达式不能用于索引类型 '{}' 属性 '[POST_TYPE.POST]' 在类型 '{}' 上不存在;
在具有如下接口的函数上使用 reduce 时出错:
// enum
export const enum POST_TYPE {
POST = 'POST',
BOARD = 'BOARD',
...
}
// interface
export interface Post {
postType?: POST_TYPE[];
}
export interface PostType {
POST?: boolean;
BOARD?: boolean;
}
// function
const exec = (prevType: Post['postType'], type: PostType) => {
const prevObject = prevType.reduce((prev, it) => {
prev[it] = true; -->> ERROR in prev[it]
return prev;
}, {});
}
我犯了什么错误?
一个问题是您的参数prevType: Post['postType']
可能是undefined
,因为Post['postType']
可能是undefined
。 不确定您要在那里做什么,但可能需要在Post
上设置postType
属性,并在将对象传递给exec
之前进行类型检查。
在代码中,第二个参数传递到reduce
缺少一个type -它只是一个普通的对象,你没有一个类型参数传递给.reduce
,所以打字稿不会让你随心所欲的键值对添加到它。
如果将类型参数传递给reduce
,这将表示初始值和累加器的类型。 在这里,因为类型将是一个具有POST_TYPE
部分属性的POST_TYPE
,所以创建这样一个对象类型并使用Partial
。 然后你可以断言返回值是一个完整的对象(没有缺少属性):
export interface Post {
postType: POST_TYPE[];
}
const exec = (prevType: Post['postType']) => {
type PostObj = {
[T in POST_TYPE]: boolean;
};
const prevObject = prevType.reduce<Partial<PostObj>>((prev, it) => {
prev[it] = true;
return prev;
}, {}) as PostObj;
};
但是, reduce
有点冗长,而且在创建单个对象时可能不是正确的工具。 仅声明对象并分配给其属性可能更合适,或者使用Object.fromEntries
:
const postObj = Object.fromEntries(
prevType.map(it => [it, true])
) as PostObj;
(不幸的是,TS 似乎还不能充分推断fromEntries
的返回值的类型,因此需要类型断言)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.