adviner
adviner

Reputation: 3567

Typescript Object.assign() alternative fix?

I'm trying to figure out how to make the following code work.

File: foo.ts

const Foo = () => {

    const api = {

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

    return api;
};

export default Foo;

File: 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;

In my tsconfig.json I have "target": "es6" set. When I use Object.assign(), api.address() gives an error:

Property 'address' does not exist on type '{ name(): void; }'.

I've researched this and the recommendation is to use the spread operator. I've tried

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

which I'm not 100% sure is correct. But I get the same error as above.

When I mouse over api in bar.ts it shows that only name exists

let api: { name(): void; }

Any advice on what I'm doing incorrectly in my code?

Upvotes: 0

Views: 255

Answers (1)

Maciej Sikora
Maciej Sikora

Reputation: 20162

The issue was not where you were looking it. Nothing wrong is with Object.assign or spread in your example. The wrong element is in address function where you are referring to api which does not exists at this point. The fix is to just create it before and have it in the scope.

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)
};

Upvotes: 2

Related Questions