如何在使用Typescript的函数中包含输出参数?

use*_*679 27 typescript

是否可以在TypeScript函数中包含输出参数?像Func1(string val1, int out k1, int out k2)C#中的东西.

Fen*_*ton 20

不是现在.

您可以返回可包含多个属性的对象.

return { k1: 5, k2: 99 };
Run Code Online (Sandbox Code Playgroud)

你可以将它与解构结合起来,使中间对象变得不可见......

function myFunction() {
    return { k1: 5, k2: 99 };
}

const { k1, k2 } = myFunction();

console.log(k1);
console.log(k2);
Run Code Online (Sandbox Code Playgroud)

您也可以使用元组实现相同的功能,但这非常易读.


Fin*_*ame 5

这是另一种方法。定义一个回调函数,其中包含您的输出参数:

function Func1(val1: string, out: (k1: number, k2: number) => void): void {
    out(1, 2);
}
Run Code Online (Sandbox Code Playgroud)

如何使用它的示例:

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
}
Run Code Online (Sandbox Code Playgroud)

我发现它对于这样的事情最有用:

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}`);
    });
}
Run Code Online (Sandbox Code Playgroud)