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?
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.
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!
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.
?
means optionnal parameter
not nullable type
.
You should use this:
Promise<User|null>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With