Alb*_*erk 3 async-await es6-promise flowtype
再生产 :
// @flow
type A = { key: string, value: string};
const a:A = {
key: 'a',
value: 'a'
};
const foo = ():Promise<A> => {
return new Promise(function(resolve, reject){
setTimeout(function(){
resolve(a);
}, 1000);
});
}
const bar = async ():A => {
const res:A = ((await foo()):any);
return res;
}
bar();
Run Code Online (Sandbox Code Playgroud)
背景:
当调用一个名为'foo'的函数返回一个带有await的promise时,变量的类型仍然是Promise.
如果我们只返回变量,Flow会正确解释该值,但如果我们输入名为'bar'的函数的返回值,则会触发错误.
19: return res;
^ Cannot return `res` because property `key` is missing in `Promise` [1] but exists in `A` [2].
References:
[LIB] static/v0.75.0/flowlib/core.js:583: declare class Promise<+R> {
^ [1]
17: const bar = async ():A => {
^ [2]
Run Code Online (Sandbox Code Playgroud)
解决方案:
相关问题:
https://github.com/facebook/flow/issues/5294
这个问题的目的:
我主要是在找一个解决方法
这似乎是一个简单的误解,但来自Flow的错误消息并不是很有用.
你已经宣布bar为
const bar = async (): A => {
Run Code Online (Sandbox Code Playgroud)
但异步函数总是返回promises,所以它应该是
const bar = async (): Promise<A> => {
Run Code Online (Sandbox Code Playgroud)
你可以在flow.org/try上看到它.