Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: cast function call to non-null

For example:

const order = await Order.findById(orderId);

then:

order.thing = something;

Warns that order may be null.

This can be silenced with:

order!.thing = something;

My question is: is there a way to specify that the order will not be null when initializing it?

e.g. is there something like:

const order = await Order.findById(orderId)!;

or

const order! = await Order.findById(orderId);
like image 653
Colin Ricardo Avatar asked Feb 04 '26 15:02

Colin Ricardo


1 Answers

The return type of Order.findById is presumably Promise<WhatEver | null>. So you want to actually use the non-null assertion on the unwrapped value of the promise.

// here, typeof order does not include `| null`
const order = (await Order.findById(orderId))!
like image 176
CollinD Avatar answered Feb 07 '26 03:02

CollinD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!