Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript function to return nullable Promise

Tags:

I'm trying to create a function that returns a Promise with values that can be resolved to null.

Basically something like this:

static getUserById(ids: String): Promise<?User> {   // do something } 

but it is returning an error

Generic type 'Promise' requires 1 type argument(s)

How to create a function in TypeScript that can return a Promise with nullable resolved values?

like image 511
Stanley Avatar asked Jul 10 '17 09:07

Stanley


People also ask

How do I return a null promise?

To return an empty promise with JavaScript, we can use an async function or call Promise. resolve . to create 2 functions that returns empty promises. p1 is an async function, so it's a function that always returns a promise.

How do I return a promise from a TypeScript?

Use the Awaited utility type to get the return type of a promise in TypeScript, e.g. type A = Awaited<Promise<string>> . The Awaited utility type is used to recursively unwrap Promises and get their return type. Copied!

How do you define a promise type in TypeScript?

In TypeScript, promise type takes an inner function, which further accepts resolve and rejects as parameters. Promise accepts a callback function as parameters, and in turn, the callback function accepts two other parameters, resolve and reject. If the condition is true, then resolve is returned; else, returns reject.


1 Answers

? means optionnal parameter not nullable type.

You should use this:

Promise<User|null> 
like image 167
ADreNaLiNe-DJ Avatar answered Oct 12 '22 17:10

ADreNaLiNe-DJ