TypeScript中的等待类型
我在JavaScript中经常使用async/await。现在,我正在逐步将代码库的某些部分转换为TypeScript 在某些情况下,我的函数接受将被调用和等待的函数。这意味着它可以返回一个承诺,只是一个同步值。我已经为此定义了TypeScript中的等待类型,typescript,async-await,Typescript,Async Await,我在JavaScript中经常使用async/await。现在,我正在逐步将代码库的某些部分转换为TypeScript 在某些情况下,我的函数接受将被调用和等待的函数。这意味着它可以返回一个承诺,只是一个同步值。我已经为此定义了waitiable类型 type waitiable=T | Promise; 异步函数增量(getNumber:()=>等待):承诺{ const num=wait getNumber(); 返回num+1; } 可以这样称呼: // logs 43 incremen
waitiable
类型
type waitiable=T | Promise;
异步函数增量(getNumber:()=>等待):承诺{
const num=wait getNumber();
返回num+1;
}
可以这样称呼:
// logs 43
increment(() => 42).then(result => {console.log(result)})
// logs 43
increment(() => Promise.resolve(42)).then(result => {console.log(result)})
这很有效。但是,必须为我所有使用async/await和TypeScript的项目指定Awaitable
,这很烦人
我真的不敢相信这样的型号没有内置,但我找不到。TypeScript是否有内置的等待类型
async/await
将始终导致语句被包装成承诺,因此您的函数将始终返回承诺等待类型可能只是多余的
async函数测试(){
const foo=等待5;
console.log(foo);
const bar=等待“你好世界”;
控制台日志(bar);
const foobar=wait Promise.resolve('really async');
console.log(foobar);
}
test();
您不需要额外键入imho,因为您的函数将始终具有:
异步函数foo(任务:()=>T|Promise):Promise{
const result=等待任务();
返回结果;
}
我相信这个问题的答案是:不,没有内置类型 在and中,他们对您的
可等待的
将有意义的各个地方使用T | PromiseLike
,例如:
/**
* Represents the completion of an asynchronous operation
*/
interface Promise<T> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
/**
* Attaches a callback for only the rejection of the Promise.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of the callback.
*/
catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>;
}
到底是什么问题?为什么需要在代码库中的任何地方指定
可等待的?无论是函数返回T
还是Promise
,函数都可以处理它。因此typeawaitable=T | Promise
没有那么复杂,在多个项目中编写它会有那么大的难度problem@Aron但如果有多个返回行,则必须将每个同步值包装在一个承诺中,这还不错,但你不必这么做。@Aron这是一种添加到帖子中的内容<如果您使用Promise
作为签名,则code>()=>42
无效,但您可以在typescript中调用wait 42
。@T.J.Crowder我创建了一个我不知道这是如何回答问题的。OP清楚地知道await
是如何工作的,并且您可以等待一个不可用的消息。问题是如何定义回调的类型,以便为回调参数提供的函数可以是函数返回T
或函数返回Promise
。这应该会有所帮助,因为:1<代码>可等待
是冗余的,因为默认情况下所有内容都是可等待的;2.只要您使用async/await
关键字,那么您的函数将始终返回一个承诺,因此键入总是一致的(imho)。不,Awaitable
不是多余的。(继续我上面的评论,因为链接占用了评论限制。)OP特别希望通过正确的键入来满足返回承诺和不返回承诺的回调。@t.J.Crowder是正确的。我想指定等待的回调函数的返回类型。
type Awaitable<T> = T | PromiseLike<T>;