Reputation: 24093
In typescript with react, I have the following situation:
if (isEdit && !itemToEdit) {
return <StepSpinner />;
}
...
...
return <MyComponent itemId={itemToEdit.id} />;
itemToEdit
definition is itemToEdit?: Item;
(optional).
Typescript gives me an error: Object is possibly 'undefined'
.
If I change the condition to if (!itemToEdit) {
, the error disappear.
How can I tell typescript "trust me, this is not undefined"?
In my real world code I have many usages of itemToEdit
and I don't want to use casting because those are points of failure.
Is there any solution to such case?
Upvotes: 1
Views: 52
Reputation: 16302
If you are sure that itemToEdit cannot be undefined, you can use TypeScript's non-null assertion operator.
itemToEdit!.id
This simply tells TypeScript, trust me, it's fine.
Upvotes: 2