typescript - 类型 '' 没有调用签名.ts(2349) && 类型 '' 必须有一个返回 iterator.ts(2488) 的 '[Symbol.iterator]()' 方法
问题描述
我正在尝试使用打字稿记录。我的精简代码如下所示:
private addTestObject() {
let testObject : TestObject = {
ref: "refererence",
summary: " blah blah..."
};
let key = "first";
this.docJson.test?.push(key, testObject);
this.docJson.test?[key] = testObject;
}
}
export interface TestObject {
ref?: string;
summary?: string;
}
export interface OpenAPI2Object {
swagger?: string; // required
paths?: Record<string, PathItemObject>;
test?: Record<string, TestObject>;
}
因为this.docJson.test?.push(key, testObject);
我得到一个错误:
测试对象 | undefined 此表达式不可调用。类型“TestObject”没有调用签名.ts(2349)
而对于this.docJson.test?[key] = testObject;
,我得到错误:
let key: string 类型 'TestObject' 必须有一个返回 iterator.ts(2488) 的 'Symbol.iterator' 方法
现在,我可以这样做:
this.docJson.test = {"first": testObject};
this.docJson.test = {...this.docJson.test, "second": testObject};
但这看起来很可怕!另外,我不能对键使用文字。直到运行时我才会知道它们——它们最终会被传递到函数中。我确信有一种正确的方法可以做到这一点......应该如何正确使用这些类型?似乎他们没有很好的记录。
更新 我发现了一些解决方法 - 分散在以下片段中:
let key = "first";
let key2 = "second";
let temp : Record<string, TestObject> = {};
temp[key] = testObject;
temp[key2] = testObject;
this.docJson.test = {...this.docJson.test, ...temp};
this.docJson.test = {...this.docJson.test, "second": testObject};
this.docJson.test["three"] = testObject;
仍然不相信这是真的正确。渴望得到一个“正确”的答案。
解决方案
推荐阅读
- python - Django:拥有超过 60 个字段的模型好不好?以及开发项目的最佳方式
- python - 获取列表的所有连续段的最快方法
- node.js - 如果其他用户最近删除了它的父级,如何防止创建数据?
- python - PyQT 退出应用程序事件
- python - 是否有一个函数可以根据 Python 和 Flask 中输入值的变化更新过滤字典?
- javascript - 多个复选框启用显示文本,禁用使用javascript删除文本?
- react-native - Flatlist 不显示来自 useContext 的列表
- rust - 如何使用 rpmbuild 打包 Rust 应用程序?
- rhapsody - 当我完成 eclipse 插件项目时如何创建 Rhapsody 自定义配置文件
- vue.js - 下拉引导程序不打开