【问题标题】:Typescript Object.assign() alternative fix?Typescript Object.assign() 替代修复?
【发布时间】:2019-11-17 19:14:50
【问题描述】:

我正在尝试弄清楚如何使以下代码正常工作。

文件:foo.ts

const Foo = () => {

    const api = {

        address: (): string => {
            return '';
        }
    };

    return api;
};

export default Foo;

文件:bar.ts

import Foo from './foo';

const Bar = () => {

    let api = {

        name: (): void => {
            const add = api.address();
        }
    };

    Object.assign(api, Foo());
    or
    api = { ...api, ...Foo() };

    return api;
};

export default Bar;

在我的 tsconfig.json 中,我设置了 "target": "es6"。当我使用 Object.assign() 时,api.address() 会报错:

类型 '{ name(): void; 上不存在属性 'address' }'。

我对此进行了研究,建议使用扩展运算符。我试过了

api = { ...api, ...Foo() };

我不是 100% 肯定是正确的。但是我得到了和上面一样的错误。

当我将鼠标悬停在 bar.ts 中的 api 上时,它显示只有名称存在

让 api: { 名称():无效; }

关于我在代码中做错了什么有什么建议吗?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    问题不在于您在哪里查看。在您的示例中, Object.assign 或 spread 没有任何问题。错误的元素在address 函数中,您指的是api,此时不存在。解决方法是在之前创建它并将其包含在范围内。

    const Bar = () => {
    
      const api = Foo(); // creation of api instance
      const extApi = {
        name: (): void => {
          const add = api.address(); // referring to the instance, here was the error
        }
      };
      return { ...api, ...extApi }; // or Object.assign(api, extApi)
    };
    

    【讨论】:

    • let api = { ...Foo(), name: (): void => { const add = api.address(); } }; 也可以。
    • 谢谢。这两个示例都为我清除了它以及为什么它不起作用。我在想关于地址的同样事情只是没有被 Bar 看到。你们帮助使它在视觉上对我有意义。谢谢
    猜你喜欢
    • 2017-04-29
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    • 2018-08-29
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多