Skip to content

Using an object from state that could be null #792

Discussion options

You must be logged in to vote

There shouldn't be anything wrong with this. This is the reason the ! operator exists, to quote from https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#non-null-assertion-operator-postfix-

Just like other type assertions, this doesn’t change the runtime behavior of your code, so it’s important to only use ! when you know that the value can’t be null or undefined.

We use the SomeInterface | null type a lot in our stores, it works fine to use the ! postfix operator in some cases.

In other cases where we cannot be sure that it exists (or want something a bit more bulletproof) we do something like:

<!-- Use a ternary -->
<template>
  <span>Hello {{ user ? user.firstName : ''…

Replies: 2 comments 2 replies

Comment options

You must be logged in to vote
1 reply
@jasonlewis
Comment options

Answer selected by jasonlewis
Comment options

You must be logged in to vote
1 reply
@Atomic71
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
4 participants