A series of OR interfaces in TypeScript Interface

Imagine a scenario where there is a choice between multiple interfaces

interface a {x:string}
interface b {y:string}
interface c {z:string}
type all = a | b | c

Now, consider an object fulfilling all by being of type c

When you try to access the property 'z' by calling:

    if (obj.hasOwnProperty('z')) {
      return obj.z
    }

You encounter a compilation error:

The code fails to compile because:

Property 'z' does not exist on type 'a'.

What would be your approach to resolve this issue?

Answer №1

If you're in a situation where replacing hasOwnProperty with in is suitable and you're not interested in creating custom type guards, using the in operator will get the job done:

interface a { x: string }
interface b { y: string }
interface c { z: string }
type all = a | b | c;

function foo(obj: all) {
  if ('z' in obj) {
    return obj.z; // obj type is narrowed to c
  }
  return undefined;
}

Check it out in the Playground

Answer №2

obj.hasOwnProperty('z') on its own does not ensure that obj meets the criteria for interface c. Imagine if obj was defined as

var obj = { x: "foo", y: "bar", z: true };

In this scenario, obj fulfills requirements for a and b, but not for c as obj.z is not a string.

To work around this, you can create custom type guards like so:

function isC(obj: all): obj is c {
  return obj.hasOwnProperty('z');
  // or return 'z' in obj;
}

...

if (isC(obj)) {
  return obj.z; // this is acceptable
}

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 causes the discrepancy in errors when dealing with subtype versus regular assignments?

Below is a sample code that has been checked by TypeScript playground https://www.typescriptlang.org/play/ interface PartialCustomData { option?: number; } interface A { [key: string]: string | PartialCustomData; } interface B extends A { [k ...

How can we use JavaScript to add a class to the <html> element?

What is the method to apply a class to the root element <html> in JavaScript? ...

"Trouble with Angular JS foreach loop: only the final item in the array

Struggling to loop through each item object in a JSON data set and evaluate its value using angular.forEach(). However, only the last item is being returned, making it impossible to perform any meaningful evaluation. Oddly enough, when using console.log(), ...

Sharing a state object with another React file can be accomplished by using props or context to

My first React file makes an API call to retrieve data and save it in the state as Data. import React, { Component } from "react"; import axios from "axios"; import Layout from "./Layout"; class Db extends Component { constructor() { super(); th ...

Tricks for displaying a dynamic object tooltip in Three.js

Can anyone help me figure out how to create a HUD hint effect for a moving object? I envision something like this: An asteroid is floating through space, and when I click on it, a hint box with information pops up. I've been playing around with thi ...

Consolidation of files for Client-Code-Generation with Swagger-Codegen: What is the best way to merge all files into

Just recently started using Swagger and NodeJS, I successfully integrated Swagger into my NodeExpress application and generated typescript-client-code with Swagger-Codegen (specifically Typescript-Angular). However, the issue I am facing is that the gener ...

Saving a JavaScript array as a Redis list: A step-by-step guide

I'm trying to figure out how to save array values individually in a Redis list instead of saving the whole array as a single value. Any suggestions on how to achieve this? P.S. Please excuse my poor English. var redis = require('redis'), ...

The font family specified in the Materia UI theme is experiencing compatibility issues on browsers that are not Chrome

Having difficulty overriding some elements with a specific font, as it seems to work perfectly on Chrome but not on other browsers like Safari and FireFox. Could there be something overlooked? Below is the code snippet: const customTheme = createMuiTheme( ...

The Socket.io client establishes connections with multiple servers simultaneously

Imagine this scenario: I am using nodejs and socket.io, and a question comes to mind. What would happen if one client establishes connections with multiple servers like this: socket = io.connect('http://server1') //600k sockets already connecte ...

Search for text in multiple tables using jQuery and automatically trigger a button click event when the text is found

I am attempting to query certain tables and click a button within a cell of a specific table. Below is the code I am currently using: links[1].click(); iimPlayCode('WAIT SECONDS = 2') var compTabs = window.content.document.getElementById(' ...

Having difficulties achieving successful API requests in Next.js and Snipcart

I'm currently diving into the world of Snipcart, and I'm encountering some issues connecting to your API. I'm using Next.js and haven't been able to find any solutions on the forum or in the documentation that address my specific proble ...

I am curious if there is a wysiwyg web editor extension specifically designed for VS2010 available?

In my experience, I have been working with C#, HTML coding using VS2010 and MVC. Utilizing VS2010 has proven to be an invaluable tool for me in this process. Currently, I find myself needing to create some straightforward static web pages. I am wondering ...

How can I use console.log to display a message when a variable reaches a specific value?

As a beginner coder, I am struggling to find the solution to this coding issue. Here is the code snippet that I have attempted: var X = "Angry"; if X = "Angry" console.log(X is Angry) After running this code, I encountered an error message specifically p ...

Looks like an error has occurred: "Swal has not been defined"

I'm currently working on a small project that involves using CodeIgniter, VueJs, and the Sweet Alert Javascript library. However, I encountered an error in my console stating ReferenceError: "Swal is not defined" when I try to call swall.fire({}) with ...

Steps for displaying the output of a post request in printing

I am currently working on creating a basic search bar functionality for daycares based on user input. I am utilizing a post request to an API and receiving back a list of daycares that match the input. Below is the code snippet: <template> <div ...

How to organize and reuse code efficiently with Node.js, EJS, and front-end JavaScript?

It seems that I may have chosen the wrong platform by posting this question on the 'Software Engineering' exchange: Currently, my focus is on learning the MEAN stack (I have yet to dive into Angular, so for now I am using pure vanilla JS for the ...

Combining an Editor and Dropdown Feature for a Single Attribute in Asp.Net MVC

How can I implement both an Editor and a Dropdown list for a single field? In the scenario where an agency is not already in the database, the user should be able to enter the agency name. Otherwise, the value should be selected from a dropdown list. I n ...

Ways to extend the default timeout duration in Angular

My server calls are taking a long time, around 30-40 minutes, and my Angular frontend is timing out. Is there a way to increase the default timeout for this service call? method1(id: number): Promise<number> { const body= JSON.stringify(id); ...

The key to successful filtering in Next.js with Hasura is timing - it's always a step

I am fetching data from Hasura using useRecipe_Filter and passing the searchFilter state as a variable. It seems that every time I press a key, the UI updates with one keystroke delay before filtered data is passed to the results state. const SearchBar = ( ...

Differences between MobX local state and global state

I am currently working on a React project using mobx to manage the application state. For dump components that interact with external data sources (such as ajax calls, filtering or mapping arrays), I simply manipulate the data in those components. Howeve ...