Can I receive a warning when I fail to await a Promise in TypeScript?

Viewed 128

TypeScript allows specifying the return type of functions:

function delay(ms: number): Promise<void> {
    return new Promise( resolve => setTimeout(resolve, ms) )
}

Somewhat frequently, I forget to await a function that returns a Promise:

let waited = 0 
while (accessible === false && waited < MAX_DELAY) {
  waited += DELAY_MS
  delay(DELAY_MS) // oh no, this won't work correctly
  accessible = await this.dbAccessible()
}

TypeScript (tsserver) does warn me if I await an expression that isn't a promise

'await' has no effect on the type of this expression

Can I make tsserver (or something else, like a linter) warn me if I fail to await an expression that is a promise? I know this is sometimes valid (and I have used it), but it's less common in my experience than forgetting to await a promise that I meant to await.

1 Answers

You can use TSLint's no-floating-promises rule, which enforces that

[p]romises returned by functions must be handled appropriately.

More on the rule here.

Related