Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript is there a way to pass parameter to method by reference?

Tags:

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?

like image 899
C.Frank Avatar asked Feb 24 '16 16:02

C.Frank


People also ask

How do you pass parameters in TypeScript?

If we are using C# then we can use the "param" keyword and pass the number of arguments to a function, but TypeScript doesn't have the "param" keyword. In TypeScript, we use 3 (three) dots instead of a param keyword with a variable name. The behavior is the same as with-param keywords.

Does TS pass by reference?

Pass in Arguments by ReferenceNon-primitive are passed into a function by reference, which means that the reference to the object passed in as the argument is passed into the function. The copy of the content is not made for the argument and the passed in object is modified directly.

Is TypeScript pass by value or reference?

It's always pass by value, but for objects the value of the variable is a reference. Because of this, when you pass an object and change its members, those changes persist outside of the function.

How do you pass a parameter to a method?

Parameters and Arguments Information can be passed to methods as parameter. Parameters act as variables inside the method. Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.


2 Answers

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 

EDIT: Here is a link to TypeScript Playground demo of the above: https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABMOcAUBbOATApgGwC5EBvABwCc4zcKoBPARmLBAwCNaBuRS62hgCYWbThQC+ASlIAoRIix58AOj406TANSauchTgKqq6odt16A9BcQA5OFERhcuPNkTsQUS9YgIAzjB4FC6IAOaobpQAhtAwELjKesFQIBRIigS64jIyvmB+DuxRFIgAvKS8xgJMxAAMADSV-BrCiIyI4roo6EUUkuZ5fnD4CfhwoWi9Rs0MjNJWbbn+w6Pjk8XTJvSC89aCQA

like image 138
Martin Avatar answered Sep 19 '22 15:09

Martin


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

like image 33
Tom Smykowski Avatar answered Sep 21 '22 15:09

Tom Smykowski