What is the best way to assign table rows to various interfaces in typescript?

Assuming I have the interfaces provided below:

export interface IUserRow {
    id: string,
    state: string,
    email: string,
}

export interface ITableRow {
    id: string,
    [key: string]: any;
}

export type Rows = ITableRow | IUserRow; // additional row types like IPostRow may be included in the future

Now, while working on mapping a table,

const instanceOfUser = (object: any): object is IUserRow => 'member' in object;

const determineOnRowClick = (row: Rows, onRowClick: any) => {
  if (instanceOfUser(row)) {
    // This condition is not fulfilled and always returns false
    const rowId = row.id;
    const view = row.state === 'Active' ? 'edit' : 'add';

    return onRowClick(rowId, view);
  }

  return onRowClick(row.id);
}
. . .
<TableBody className={tableClasses.tbody}>
  {rows.map((row: Rows, i: number) => (
    <TableRow
      onClick={() => determineOnRowClick(row, onRowClick ?? null)}
      key={row.id || i}
    >
. . .

I am trying to programmatically determine the onRowClick method, but the conditional statement,

if (instanceOfUser(row)) {
. . .

is never met. Is this achievable with TypeScript by declaring the current element in the map function as an element that could belong to multiple interfaces? If so, what approach should I take?

Answer №1

Discover:

function determineOnRowClick(row, onRowClick) {
  if (row.email !== undefined) {
    const rowId = row.id;
    const view = row.state === 'Active' ? 'edit' : 'add';
    return onRowClick(rowId, view);
  }

  return onRowClick(row.id);
}

If the row object does not have an email property, this function will return false. To handle this scenario, cast the row parameter as type IUserRow in order to inform TypeScript that the email attribute may be present.

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

configure various search parameters simultaneously during the rendering process

Incorporating a Tree component from mui v5, I am aiming to include searchParams for the selected and expanded nodes. This task is accomplished using the useSearchParams hook from React Router (v6). The issue arises when both the selected and expanded even ...

The MVC Controller is unable to retrieve decimal values from an Ajax POST request

I am facing an issue with the POST function in my code. While string and integer values are reaching the Controller without any problem, double values are not being received on the server side. Interestingly, when I test on my local machine, everything wor ...

Retrieve the student ID from the URL parameters and display all records with the matching ID

I am trying to display all rows with the same id using $_GET['student_id'], but I am encountering an error with Datatables. Here is my code. When I get the id from the URL, for example: example.com/example.php?=2222 All rows with the id 2222 wil ...

Placing a group of input fields and a button based on the data-id attribute of the element

I have a form that appears when a button is clicked, and the save button saves input values into an object. Is there a more efficient way to write this function if I need to create 9 more buttons with different data-id attributes (e.g. data-id="2" and so ...

When using the npm command, errors may occur that are directly related to the lifecycle and initialization

Currently, I am delving into the world of OpenLayers and JavaScript. I came across a helpful tutorial that provides step-by-step guidance on creating a simple OpenLayers project using JavaScript. I followed the instructions diligently but encountered an er ...

When attempting to log API results in Next.js, a TypeError occurs because the property is undefined

I'm encountering a rather unusual error. In my Next.js app, I am attempting to console log the results of an API call to see what data I receive. The API function is responsible for verifying if a user is logged in, and if they are, I render a specifi ...

Activate Pop-up for a single instance on BigCommerce

After researching and adding my own code, I am still struggling to get this question answered correctly. Here are the key points I am trying to achieve: 1. Automatically open a popup when the homepage loads. 2. Ensure that the popup is centered on all brow ...

No data being fetched through Ajax

I am facing an issue with retrieving PHP data in the form of an array. I have created an AJAX query to display data in two divs: one is a drop-down and the second is where all data will be shown. However, the problem is that when I attempt to do this, all ...

Is there a way to determine what is affecting the properties of an element?

I've been grappling with a chunk of lengthy HTML, styles, and javascript. My mission? To uncover whatever magic is changing the text within a specific element. <span class="panel-title"> I'm a Panel with All Options</span> Transform ...

Preventing HTML form submission after displaying an alert in Vanilla JavaScript

I have created a quiz using HTML with validation. The next step is to score the quiz in JavaScript. The scoring system works fine, but I want to prevent the form from posting to result.html if the user scores 0 on the quiz. I've managed to display an ...

Stopping the sound when its' Div is hovered over

I've managed to successfully trigger the audio to play on hover, but I'm having trouble getting it to pause when my mouse leaves the area. Check out the code in action here: https://jsfiddle.net/jzhang172/nLm9bxnw/1/ $(document).ready(functio ...

Error: Sorry, there was an issue with the code (React)

I'm attempting to build a React project without Node, and I'm trying to call a JS file from an HTML file. This is just a simple example for learning purposes. However, I keep encountering the Uncaught SyntaxError: Unexpected token '<&apos ...

Troubleshooting Issue: Failure of Ajax Script to Display Saved Data in Edit Function

Whenever I clicked on the Edit icon in the action column of my data tables, the saved data did not display as expected. I noticed that this issue was only occurring for file input types, while it worked properly for text input types. In the Blade file Ad ...

Visualization of pie charts in Angular2 using Google library

Currently, I am in the process of building a web application using Angular2 that includes a Google pie chart. One of the components of the application is a Directive specifically designed for the pie chart. Below is the code snippet for the Directive: @D ...

How to maintain the focus within a jQuery dialog box

Exploring the world of jQuery dialog, I'm eager to incorporate it into my latest side project. My goal is to enhance accessibility by adding tabindex to the divs within the dialog for easy tab navigation. However, I encountered an issue where the focu ...

Alexa Skill: Successful with the initial query but fails with the subsequent one

An issue has been identified with the Alexa skill where it works for the first question but not the second one. The skill involves a jumbled letters quiz utilizing the following array: var arr = [{"Q":"dcha","A":"chad"},{"Q":"goto","A":"togo"},{"Q":"alim" ...

The "track by" feature in Angular doesn't seem to be functioning properly when used with an array from $

Within the method of my factory, I am retrieving an array from the server using Angular's $resource: var resource = $resource("vm", { session: function() { return Auth.token(); }, all: '@all', vmId: '@vmId' ...

Angular encountered an issue with an HTTP POST request, as the 'Access-Control-Allow-Origin' header was not found on the requested resource

I have been attempting to transmit data to a servlet using Angular HTTP POST requests. var httpPostData = function (postparameters, postData){ var headers = { 'Access-Control-Allow-Origin' : '*', &a ...

Understanding Namespacing in Vuex with Vue.js

Trying to organize modules' getters, mutations, and actions with namespacing can be a bit challenging. I came across this document, but it didn't provide clear enough information for me. // types.js // Constants for namespacing getters, actio ...

Guide to adding a JS file from npm package to a new page in Nuxt.js

I am facing an issue where I have multiple npm packages containing client-side scripts that I need to include in different pages of my Nuxt.js project. I attempted to achieve this by using the following method: <script> export default { head: { ...