35

I have method that gets parameters and in this method there are calculations that change the parameters value. When returning from the method the parameters continue to other methods for more calculations.

Is there a way to pass parameter to method by reference or the only way is by i join the parameters to object and return them?

3
  • 1
    Possible duplicate of How do I include output parameters in a function with Typescript? Commented Feb 24, 2016 at 16:05
  • I would simply pass them as an object. It's easy to reason about and people who will read your code will understand it. :) Commented Feb 24, 2016 at 16:11
  • Eiver thanks for you'r answer, I saw this question so there is no way to pass by ref.the only in TS is to return object. Commented Feb 24, 2016 at 16:24

2 Answers 2

53

With JavaScript, and TypeScript, you can pass an object by reference -- but not a value by reference. Therefore box your values into an object.

So instead of:

 function foo(value1: number, value2: number) {
     value1++;
     value2++;
 }

Do:

function foo(model: {property1: number; property2: number}) {
     model.property1++;
     model.property2++;

     // Not needed but
     // considered good practice.
     return model;
}

const bar = { property1: 0, property2: 1 };
foo(bar);

console.log(bar.property1) // 1
console.log(bar.property2) // 2

See full demo on TS Playground

Sign up to request clarification or add additional context in comments.

8 Comments

how do you call such function to impact the calling actual parameter v1, v2? Is it like so this.foo( {property1: v1, property2: v2 } ) ; ? Thank you.
@marie may, you would need to define the object, and refer to the members of that object -- which will get updated by reference.
@Arkilo this absolutely works. I have included a link to TypeScript playground of the above solution.
That is not passing by reference to a function. The original question was about passing by reference to a function, not using a method to update a member's properties.
How is it not passing by reference? The function is taking an object which by definition is always passed by reference. You are literally doing the same thing here
|
-4

You can pass property name (and object if necessary) to a method

Comments

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.