TypeScript's Conditional interface is a powerful feature that allows for

I am facing a scenario where I have two distinct interfaces (A, B) and a function that accepts a parameter props as a conditional interface/union type. However, I am unable to utilize the prop if it is not declared in both interfaces.

Check out this example here:

interface A {
    name: string
};

interface B {
    age: number
};

function foo(props: A | B) {
    return props.name;
}

Answer №1

It is important to consider that you may not know if the name key exists on the props object.

You have a couple of choices:

1

function foo(props: A | B): string | undefined {
  if ('name' in props) {
    return props.name
  }
}

2.

interface A {
  name: string
  age?: undefined
}

interface B {
  name?: undefined
  age: number
}

function foo(props: A | B): string | undefined {
  return props.name
}

Why?

Typescript is alerting you because an object missing the name key is different from an object where the name key is undefined. Consider this scenario:

const a = {
  // name is missing
  age: 1
}

const b = {
  name: 'test',
  age: undefined
}

Object.keys(a) == ['age']
Object.keys(b) == ['name', 'age']

if ('age' in b) {
  console.log('this is true')
}

if ('name' in a) {
  throw new Error(`This is false`)
}

Answer №2

Here is one way you could achieve the desired outcome:

function bar(input: X | Y) {
    if ((input as X).label) {
        return (input as X).label;
    }
    return undefined;
}

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

Hiding or removing a div element after making a deletion request using AJAX in

After fetching an image with a dynamic "id" and successfully deleting it using ajax, the issue arises when trying to dynamically hide the deleted image div. Below is the HTML code: <?php $banner=$store->banner; if(!empty($banner)) { ...

Utilizing Vue 3 to transform an item within a list by referencing its index

Storing the element's index in a global variable is causing issues when trying to individually edit each of them. Adding multiple elements with similar properties but being unable to edit them separately due to alterations affecting the rest is a chal ...

Modify content for slideToggle

Check out this jfiddle link: http://jsfiddle.net/RHbzv/ I'm attempting to change the text from 'See more' to 'See less' when displaying the answer, but I can't seem to make it work. Here's what I've tried: $(&ap ...

Modify the text of a button depending on the condition and user interaction within an ng-repeat loop in AngularJS

I have a scenario where I am displaying a list of users with two buttons for Start and End using the ng-repeat code: <div class="list-group" ng-repeat="patient in patients" > <a href="#" class="list-group-item" ng-click="chat ...

Ways to showcase the content of a page once the controller variables have been set

As someone who is just starting out with AngularJS and web development, I am curious to know if there is a way to delay the display of a page until after all of the controller's $scope variables have been initialized. Most of my $scope variables are c ...

Password validation with Mongoose customization

I'm working on creating a Schema using mongoose, but I'm facing some challenges when it comes to implementing custom validation for the password. The password should meet the following criteria: It must contain at least one special character ...

What is the process for integrating unit tests from external sources into an Angular project following an upgrade to version 15

As of Angular v15, the require.context function has been removed from the test.ts configuration file. I used to rely on require.context to expose tests outside of the Angular project to Karma. Now that it's no longer available: const contextGlobal = ...

Removing a similar object from an array using JavaScript

Working on a d3 force graph, I aimed for smooth updates using the method shown in the Modifying a Force Layout example. However, my goal was to achieve dynamic updating behavior unlike the static example provided. After calling initializeGraphData(json); i ...

Is it possible to execute a task following a particular Websocket.send() in JavaScript?

After sending a message to a websocket, I am trying to send a POST request using callbacks. I attempted the following approaches: socket.send(message,function(){...}); and function sendsocket(message, callback){ socket.send(message); callback; } and ca ...

verify selection on php page using javascript

I'm having trouble with confirming the deletion of something. Despite getting an alert message when clicking the 'deleteReply' button, nothing else appears to be happening. I've tried echoing the posted variable but it's not workin ...

Synchronously retrieving JSON data from a URL using JavaScript

I'm currently working on extracting the title of a YouTube video using jQuery to parse JSON. The issue I am facing is that it works asynchronously, resulting in the answer being displayed after the page has already loaded. Here's the current resu ...

Setting up a Node.js application with Nginx on DigitalOcean

While running my application on a DigitalOcean droplet using nginx, I encountered a peculiar issue. The app runs perfectly fine with http, but when switching to https, nginx throws a 502 BAD GATEWAY error. Despite trying various DigitalOcean guides and sco ...

The JavaScript event responsible for reloading the page is triggering every time the page is refreshed, resulting in an endless loop

Initially, the issue does not arise, however, it only occurs when the event is triggered by reordering the column, causing an automatic reload afterwards. tabelaProdutos.on('column-reorder', function(e, settings, details) { ... location ...

Updating the key within an array of objects

In my array of objects, I have the following data: arrayOfObject = [{'key1': [1,2]} , {'key2': [1,2,3]} , {'key3': [1,2,4]}] I know the name of the key that I want to replace in my array : var keyString = 'key1&apos ...

Transitioning from using .live() to utilizing the .on() method

I am facing an issue with my code that is responsible for drawing newly added comments. After switching from using live to on, the code does not work on elements added after the page has loaded. Below is the code in question: $(function(){ $('.s ...

Why are Ajax calls returning 404 in Google Cloud Platform but working perfectly on local servers?

I recently came across a fantastic repository that offers a Java REPL directly in the browser. I decided to fork it and deploy it as a Google Cloud app to enhance its security with HTTPS. Everything seems to be working smoothly, except for one issue: Unf ...

Angular 8: Syncing Component Values with Service Updates

My Angular 8 project features two sibling components that utilize a service to manage restaurant data. One component displays a list of restaurants fetched from an api, while the other component filters the displayed restaurants based on user input. Despit ...

Selenium IDE's float calculation in javascript results in a value of 1 instead of the expected 1.99

I am trying to perform a JavaScript evaluation in Selenium IDE that involves multiplying 3 decimal values. javascript{parseFloat(storedVars['val1'])*parseFloat(storedVars['val2'])*parseFloat(storedVars['val3'])} However, whe ...

Ways to expand the `Array.prototype` from an external library in a Node.js environment

While enjoying my time on hackerrank with pure JavaScript, I decided to steer clear of extra arrays or math libraries, unlike the convenience of using python. My approach is robust, but now I'm considering utilizing sugar.js or underscore. I came acr ...

What is the best way to input an HTML element into AngularJS code?

I am looking to integrate the html element into my angularjs code. Within my HTML, I have elements such as data-form-selector='#linechart_general_form' and data-url="{% url 'horizon:admin:metering:samples'%}" that I need to access withi ...