DEV Community

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

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.