typescript-typings - 如何将索引签名分配给对象的值?
问题描述
给出以下代码:
export function objToStr(object: object): string {
let str = [];
for (let p in object) {
if (object.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(object[p]))
}
}
return str.join("&")
}
我从以下错误中得到错误object[p]
:
Element implicitly has an 'any' type because type '{}' has no index signature. [7017]
我试过了
encodeURIComponent((<any>object[p]))
encodeURIComponent(object[p]: any)
但我仍然得到错误。我发现打字一切都很混乱,那里有很多类型。
如果有人能告诉我 Typescript 想从我那里得到什么,那会很有帮助,这是最后一条错误消息,然后我将代码从 JS 切换到 TS。
编辑
我必须添加"noImplicitAny": true
以测试设置,因为我不确定正在做什么以及代码将如何对其做出反应。
把它变成假我现在得到:
Argument of type 'string' is not assignable to parameter of type 'never'. [2345]
对于现场部分str.push
解决方案
出现错误是因为您compilerOptions.noImplicitAny = true
在 tsconfig.json 中有。如错误所示,将索引签名添加到object
变量:
let object: { [index: string]: any } = {};
let str: string[] = [];
ieany
将被明确指定。
推荐阅读
- ruby-on-rails - 试图从一个类继承并在其上添加一个属性,得到一个 TypeError
- java - WebView 可以像浏览器一样吗?
- visual-studio - 如何在 Visual Studio 中将代码格式重置为默认设置?(无需重置我的所有设置)
- apache-flink - 为什么存在 BucketingSink 时我们需要 StreamingFileSink?
- reactjs - 谷歌地图反应标记和列表
- c# - .Net MVC Core Policy 基于 JWT 的授权
- docker - 为什么我的 docker build 在 jenkins 代理上失败?
- android - 使用Android相机进行人脸检测。?
- matlab - MATLAB - 如何定义多变量目标优化
- python - 使用列表从 CVS 文件创建字典