如何使用 Typescript 在函数中包含输出参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14115278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I include output parameters in a function with Typescript?
提问by user1941679
Is it possible to include output parameters in a function with TypeScript?
Something like Func1(string val1, int out k1, int out k2)
in C#.
是否可以使用 TypeScript 在函数中包含输出参数?类似于Func1(string val1, int out k1, int out k2)
C# 中的东西。
回答by Fenton
Not currently.
不是现在。
You can return an object that can contain more than one property.
您可以返回一个可以包含多个属性的对象。
return { k1: 5, k2: 99 };
You can combine this with destructuring so the intermediate object becomes invisible...
您可以将其与解构结合起来,使中间对象变得不可见......
function myFunction() {
return { k1: 5, k2: 99 };
}
const { k1, k2 } = myFunction();
console.log(k1);
console.log(k2);
You could also achieve the same with a tuple, but this is pretty readable.
你也可以用元组来实现同样的效果,但这是非常易读的。
回答by John Papa
Generally, you just return an object with multiple properties, one of which contains your function. Something like this:
通常,您只需返回一个具有多个属性的对象,其中一个包含您的函数。像这样的东西:
var foo = function (val1 : string){
// do something
return {
k1: 22,
k2: 33
};
}
You could also make it implement an interface, so you know what to expect as the returned object.
你也可以让它实现一个接口,这样你就知道返回的对象是什么。
interface IFoo {
(val1: string): INumbers;
}
interface INumbers {
k1 : number;
k2 : number;
}
var foo : IFoo = (val1 : string){
// do something
return {
k1: 22,
k2: 33
};
}
回答by lhk
Typescript passes all parameters with "call by value". But if the parameter is a reference this behaves similarly to "call by reference" most of the time. You can write wrapper classes for primitive types. Here's some code:
打字稿通过“按值调用”传递所有参数。但是,如果参数是引用,则大多数情况下它的行为类似于“按引用调用”。您可以为原始类型编写包装类。这是一些代码:
var func=function(param:Str){
param.str="modified";
}
class Str{
str:string="unmodified";
}
var test:Str=new Str();
alert(test.str); //alerts "unmodified"
func(test);
alert(test.str); //alerts "modified"
You need to be careful, though:
但是,您需要小心:
var func=function(param:Str){
param=new Str("modified");
}
class Str{
str:string;
constructor(param:string){
this.str=param;
}
}
var test:Str=new Str("unmodified");
alert(test.str); //alerts "unmodified"
func(test);
alert(test.str); //alerts "unmodified"
The function parameter is passed "call by value". Therefore inside the function body you're working with a copy of a reference. This reference points to the same object as the reference that you passed as a parameter, so you can access its members and modify them. But if you assign a new object to the reference all further changes are applied to this new object. Therefore the code above prints unmodified twice. I think C# works this way, too.
函数参数通过“按值调用”传递。因此,在函数体内,您正在使用引用的副本。此引用指向与作为参数传递的引用相同的对象,因此您可以访问其成员并修改它们。但是,如果您将一个新对象分配给该引用,则所有进一步的更改都将应用于此新对象。因此上面的代码打印两次未修改。我认为 C# 也是这样工作的。
回答by Eljay
If you really, really want to have an output parameter, even though you could return an object or an array (as a makeshift tuple object), look at foo and the call site of foo...
如果你真的,真的想要一个输出参数,即使你可以返回一个对象或一个数组(作为一个临时的元组对象),看看 foo 和 foo 的调用站点......
function p(s) {
document.body.appendChild(document.createTextNode(s));
document.body.appendChild(document.createElement('BR'));
}
function foo(output: any): void {
output.uno = 1;
output.dos = 2;
}
var o: any = {};
function foo(o);
p(o.uno + " " + o.dos);
回答by trinalbadger587
If you want to mantain C# like syntax you can use:
如果您想保留类似 C# 的语法,您可以使用:
function func(val1, k1, k2)
{
k1.v = 7;
k2.v = 9;
return "";
}
and to call it
并调用它
func("", {}, {});
回答by Jorge García Pérez-Cuba
Sometimes the parameter is undefined and you need to instantiate it inside a method. In that cases you can use "lambda functions" or "arrow functions" and simulate the output parameter with this:
有时参数未定义,您需要在方法中实例化它。在这种情况下,您可以使用“lambda 函数”或“箭头函数”并使用以下命令模拟输出参数:
example:
例子:
class classA
{
propertyA : number;
constructor(value: number){
propertyA = number;
}
}
class classB {
// ...
exampleMethod(){
let classAInstance: classA;
this.sumValueMethod((p) => classAInstance = p, 10);
if(classAInstance != undefined)
alert("Yeah");
}
sumValueMethod(paramA:(p: classA) => any, paramB: number){
let variableA: classA = new classA(0);
variableA.propertyA += paramB;
paramA(variableA);
}
}
回答by Finickyflame
Here's another way. Define a callback function which will include your out parameters :
这是另一种方式。定义一个回调函数,其中将包含您的输出参数:
function Func1(val1: string, out: (k1: number, k2: number) => void): void {
out(1, 2);
}
Example on how to use it:
如何使用它的示例:
function anotherFunction(): void {
let k1: number;
let k2: number;
Func1("something", (v1, v2) => {
k1 = v1;
k2 = v2;
});
console.log(k1); // output: 1
console.log(k2); // output: 2
}
I find it mostly useful for stuff like this:
我发现它对这样的东西最有用:
const keys: string[] = [];
const values: number[] = [];
function tryGet(key: string, out: (value: number) => void): void {
const index = keys.indexOf(key);
if (index >= 0) {
out(values[index]);
}
}
function test(): void {
const key = "myValue";
tryGet(key, (value) => {
console.log(`Key '${key}' exist with value ${value}`);
});
}