0

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?

1 Answer 1

2

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)
};
Sign up to request clarification or add additional context in comments.

2 Comments

let api = { ...Foo(), name: (): void => { const add = api.address(); } }; also works.
Thanks. Both examples cleared it up for me and why it wasn't working. I was thinking the same thing about the address was just not being seen by Bar. You guys helped make it visually make sense to me. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.