DEV Community

Discussion on: Typescript - Tips & Tricks - Non-null assertion operator

Collapse
 
jackmellis profile image
Jack

Amazing.

There are many many times that you have 100% confidence in a property's existence, but typescript does not...

Off the top of my head: response data from an api where you know that if property a has a specific value, then property b will not be null.

Another example is if you're using something like jsx-control-statements in react:

<If condition={myObj?.name != null}>
  {myObj.name}
</If>
Enter fullscreen mode Exit fullscreen mode

You can assert that a property exists, but then when you reference it on the next line, typescript is unable to infer from the control statement that myObj is not null.

I come across these issues all the time. I didn't realise this feature existed and I highly expect I'll need to use it at some point before the week is out.

Collapse
 
puppo profile image
Luca Del Puppo

I'm glad I showed you a new feature.
In your first case, you could create different types base on the response type, so you can detect the correct type if some field has or not has a specific value.
I leave you a simple case, I hope it can help you in the future.

type WsResponseOk = {
    value: true
}

type WsResponseError = {
  value: false;
  error: string;
};

type WsResponse = WsResponseOk | WsResponseError;

const getResponse = (): WsResponse => ({ value: true })

let response = getResponse();

if (response.value) {
  // response => WsResponseOk
  response.value;
  response.error; // Property 'error' does not exist on type 'WsResponseOk'.
} else {
  // response => WsResponseError
  response.value;
  response.error;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jackmellis profile image
Jack

Yes I do this but often the combinations are so complex it becomes impractical and often typescript is left unable to correctly infer which variation you're referring to. This is especially true when you're passing an object around several different functions or if you're using assertions that are out of your control that also don't offer sufficient type guarding.