首页 > 解决方案 > 类型 '' 没有调用签名.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;

仍然不相信这是真的正确。渴望得到一个“正确”的答案。

标签: typescripttypes

解决方案


推荐阅读