gpt4 book ai didi

javascript - 如何为 Flow 注释此函数

转载 作者:行者123 更新时间:2023-11-30 16:02:38 24 4
gpt4 key购买 nike

我在使用 Flow ( https://github.com/facebook/flow ) 的文件中有这个 JS 函数

// @flow
static promiseWrapper(fn, ...args) {
return new Promise(
async function(resolve, reject) {
try {
await fn(...args);
resolve();
} catch (e) {
reject(e);
}
}
)
}

我将如何对此进行注释?

最佳答案

正如在 github project issue 上讨论的那样,这将是我提出的解决方案:

class Foo {
// We are using generics <U, T> to define the input type / output type (may be the same... I don't know the use-cases)
static promiseWrapper<U, T>(fn: (...args: Array<U>) => Promise<T>, ...args: Array<U>): Promise<T> {
return new Promise(async (resolve, reject) => {
try {
// I felt like handling the return value of this await function
const ret = await fn(...args);
resolve(ret);
} catch (e) {
reject(e);
}
});
}
}


// Most of the type inference comes from this function
function fun(...args: Array<number>): Promise<string> {
const ret = args.reduce((result, num) => (result + num), 0);
return Promise.resolve(ret.toString());
}

const myProm = Foo.promiseWrapper(fun, 1, 2, 3);

// Here, total should be inferred as string, since our `fun` function returns a Promise<string>
// Generic function definition <T> picks this up correctly :-)
myProm.then((total) => {
// $ExpectError : total should be inferred as string, hence it should fail on numerical addition
const foo: number = total + 1;

});

关于javascript - 如何为 Flow 注释此函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37490255/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com