typescript - 使用 Object.keys 和减少对象键
问题描述
我正在尝试减少Object.keys
,如下所示:
const example = { hello: true }
Object.keys(example).reduce((acq, key) => {
const value = example[key]
return acq
}, {})
出于某种原因,我收到一个类型错误example[key]
(参数)键:字符串
元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{你好:布尔值; }'。在类型 '{ hello: boolean; 上找不到具有类型参数的索引签名。}'.(7053)
getKeys
我使用具有我期望的类型的泛型创建了自己的函数:
function getKeys <T>(g: T) {
return Object.keys(g) as (keyof T)[]
}
const example = { hello: true }
getKeys(example).reduce((acq, key) => {
const value = example[key]
return acq
}, {})
但是,我正在寻找是否可以不使用 wrapping Object.keys
。
解决方案
在这种情况下,您可以为您的example
变量提供 a ,如下所示,让 typescript 知道键是 type string
。
const example = { hello: true } as { [key: string]: any }
推荐阅读
- jquery - jQuery每个循环输出
- c# - 将 Microsoft 报表导出为 PDF 不显示中文字符
- javascript - 参数从哪里来?
- apache-camel - 为什么以下捆绑包处于宽限期?
- angular - 使用一个模块的组件作为应用模块路径中的路径
- powershell - 使用 Power shell 重命名驱动器中特定文件夹中的文件
- python - 在 pythonanywhere 中使用我的代码时出现 ImportError
- javascript - 使用 XHR 的异步请求
- html - 带延迟的循环动画 SVG - safari
- git - git:自动合并与正常(非冲突)合并?