Refine the search results by focusing on a specific property value

Assume I have a type defined as follows:

type Result = {error:true,response: undefined} | {error:undefined, response:{nick:string}}

This type will either contain an error property or a response, but not both.

Now, I am attempting to create a function that can handle and narrow down this result.

function unwrapResult<T extends {error: any}>(result:T) {
  if(result.error){
    throw result.error
  }
  return result
}

However, it seems like this function is not functioning as intended.

function test():Result {

  return {error:undefined,response:{nick:'iki'}}
}

const data = unwrapResult(test())
 
 data.response?.nick // response is {nick:string} | undefined

if(!data.error){
  data.response.nick // this is ok 
}

Is there a way to conditionally extract the response object so that I end up with just {response:{nick:string}} without needing the if(!data.error) check, which contradicts the purpose of the unwrapResult function?


TS Playground

Answer №1

For your scenario, the error can only be true or undefined - it cannot be an actual Error object or undefined. This means that you don't require a generic parameter to rectify the issue.

type Result = {
  error: true,
  response: undefined
} | {
  error: undefined,
  response: {
    nick: string
  }
}

function unwrapResult(result: Result) {
  if(result.error){
    throw result.error
  }

  return result
}

function test(): Result {

  return { error: undefined, response: { nick:'iki' } }
}

const data = unwrapResult(test())
 
data.response.nick

if(!data.error){
  data.response.nick
}

Playground

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason for TypeScript not providing warnings for unrealistic conditions involving 'typeof' and 'in'?

The recent updates in version 4.9 highlighted the enhanced narrowing with 'in'. Intrigued by this, I decided to experiment with their example in a coding playground. Surprisingly, I discovered that seemingly impossible conditions involving typeof ...

Do I have to create all the classes returned when consuming a JSON web service in Angular/Typescript?

I would like to access this service: https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY I am interested in extracting only two pieces of data: "location" : { " ...

Using Angular 7 to set the value of an object returned by an observable to a variable

I encountered an issue while trying to assign the return value from a service to a component. ngOnInit() { this.getInspectionData(); } getInspectionData() { this.auctionService.getInspectionResult(`df570718-018a-47d8-97a2-f943a9786536`) ...

Next.js production build encountering an infinite loading error

I have been utilizing the Next.js TypeScript starter from https://github.com/jpedroschmitz/typescript-nextjs-starter for my current project. The issue I am facing is that when I attempt to build the project after creating numerous components and files, it ...

The browser failed to display the SVG image, and the console log indicated that the promise was rejected, with the message "false."

I'm struggling to understand why my SVG isn't showing up on the screen. The console log is displaying "false," which I believe indicates that a promise was rejected Here is the TypeScript file I am working with: export class PieChartComponent im ...

Issue with building Webpack React Router DOM configuration

I recently developed a React+Typescript app with Webpack 5 configuration completely from scratch. Everything was running smoothly in development mode, and I utilized React Router DOM version 6.23.1 for routing. However, once I built the app, some component ...

Using a click event to target the next div and apply a CSS class using Typescript

I am trying to create a Typescript function that will locate the next div and apply a CSS class to it. Here is what I have attempted: <ul> <li><a href="#" onclick="toggle()">Item 1</a></li> <div class="content hide ...

Is it necessary to separate Lodash orderby functions to ensure they function correctly?

For some reason, I'm having trouble sorting my data using lodash in my front-end client code. All the examples I've come across don't involve working with data in an interface, so I can't figure out where I'm going wrong. Let&apo ...

Changing a method within a class does not automatically update how it is used in other classes that inherit from it

I am attempting to modify the alpha method in the context of the Cat class, and have the beta method reflect those modifications. const wrapperFn = <T extends (...args: any) => any> (a: T) => { return (...args: Parameters<T>) => ...

Typescript encounters an overload error on the Accumulator argument while using reduce operation

I encountered the following code snippet: const foo = ( fields: { [key: string]: string, } ) => { const { one, two } = Object.values(fields).reduce( (acc, field) => { if (isOne(field)) { return { ...acc, two: [...acc.two, ...

Update the URL for the Swagger 2.0 documentation path

This is how I set up swagger : const openapi = Openapi.initialize({ paths: openApiPaths, app, apiDoc, }); const openApiSpec = openapi.apiDoc; console.log(openApiSpec); app.use(swaggerUI(openApiSpec)); How do I update the base path ...

Launching Node Application

While working with NestJS and IIS, I encountered an issue when deploying my 'dist' folder on the server using IISNode. The error message 'module not found @nestjs/core' prompted me to install the entire 'package.json' files (n ...

What is the best way to inject a custom Angular service into a test in TypeScript without needing to mock it?

I have defined my modules and tests as shown below, but I encounter an issue when attempting to inject ContentBlocksService into the beforeEach(mock.inject((ContentBlocksService)... statement. It shows an error message saying Unknown provider ContentBlocks ...

What is the syntax for defining a generic type in TypeScript when using the property name "type"?

Is there a way to declare a generic type GetAppActions where if T is equal to trigger, only the trigger data property is displayed, and vice versa? type GetAppActionType = 'trigger' | 'action' interface AppActionInputField {} type GetA ...

Why does the onBlur event function in Chrome but fails to work in Safari?

I've encountered a problem with the onBlur event in react-typescript. To replicate the issue, I clicked the upButton repeatedly to increase the number of nights to 9 or more, which is the maximum allowed. Upon further clicking the upButton, an error m ...

Is it possible to silence the other person's audio using livekit?

As a developer, I create meeting apps using React and livekit technology. I am looking for a reliable method to silence the audio of other participants in the virtual room. Any suggestions? ...

Transferring the storage value to an Ionic 2 object

Extracting information from storage in Ionic 2. this.storage.get('name').then((nama) => { this.name = nama }); Now, I am trying to assign the extracted data "this.name" to an object. However, upon running the app, ...

Typescript errors in console not being displayed by swc-loader

I have decided to make the switch from ts-loader to swc-loader based on the guidance provided in this article. However, after completing the migration, I am encountering an issue where basic Typescript errors are not being displayed in the console. For ins ...

When trying to access the DOM from another module in nwjs, it appears to be empty

When working with modules in my nwjs application that utilize document, it appears that they are unable to access the DOM of the main page correctly. Below is a simple test demonstrating this issue. The following files are involved: package.json ... "ma ...

Changing the fill color of externally imported SVGs from a CDN: A simple guide

While working on a website project using Next JS, I came across the challenge of displaying SVG icons stored in Sanity and dynamically changing their fill color. Is it possible to achieve this feature, such as changing the color when hovering over the icon ...