Utilizing an if statement with a TypeScript DeepMap Union Type

I am attempting to create a Union type that includes optional fields in its structure. Here are the types I have defined:

export type StartEndType = {
  start_date: string;
  end_date: string;
};

export type PayrollContract = StartEndType & {
  type: 'ON_PAYROLL';
  yearly_holidays: number;
};

export type FreelanceContract = StartEndType & {
  type: 'FREELANCE';
  hourly_rate: number;
};

export type Contract = PayrollContract | FreelanceContract;

In my component, it is implemented like this:

{contractType === 'ON_PAYROLL' ? (
  <Number name="yearly_holidays"  />
) : contractType === 'FREELANCE' && (
  <Number name="hourly_rate" />
)}

When I hover over the contract, it correctly identifies it as either ON_PAYROLL or FREELANCE. However, I encounter a DeepMap error within my component.

Is this not supported by TypeScript by default?

Property 'yearly_holidays' does not exist on type 'DeepMap<PayrollContract, FieldError> | DeepMap<FreelanceContract, FieldError>'.
  Property 'yearly_holidays' does not exist on type 'DeepMap<FreelanceContract, FieldError>'.

How can this issue be resolved? Thank you in advance.

Answer №1

Do you have the code snippet for the Number component? It seems like there might be an issue with how you are displaying the number by name. I was able to successfully compile and run the TypeScript code provided above in the TS playground.

const renderPayField = (contract: Contract) => {
  if (contract.type === 'ON_PAYROLL') {
     return <Number name="yearly_holidays" />;
  }
  if (contract.type === 'FREELANCE') {
     return <Number name="hourly_rate" />
  }
  return null;
};

Furthermore, I made some updates to the TypeScript code to utilize interfaces and readonly properties for enhanced readability

export interface StartEndDate {
  start_date: string;
  end_date: string;
};

export interface PayrollContract extends StartEndDate {
  readonly type: 'ON_PAYROLL';
  yearly_holidays: number;
};

export interface FreelanceContract extends StartEndDate {
  readonly type: 'FREELANCE';
  hourly_rate: number;
};

export type Contract = PayrollContract | FreelanceContract;

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

Is it time to ditch daylight saving time - am I managing my dates and times correctly?

Currently, I am in the process of working on a PHP/mySQL web application where dates are stored as unix timestamps in columns that are UNSIGNED INT(10). When it comes to displaying these dates in the web view, we utilize moment.js to parse the numbers. On ...

Ways to recover information that is not typically found

My firebase database has two main trees: "tag" and "user". Each user is associated with a set of tags, referred to as preferences. Here is the structure of my database: https://i.sstatic.net/m98EO.jpg I am trying to display a list of preferences that a s ...

Linking together or organizing numerous JavaScript function executions in instances where the sequence of actions is crucial

I have implemented a web api method that conducts calculations by using a json object posted to the method. I believe that a jquery post is asynchronous. Assuming this, I want to be able to link multiple calls to the js function invoking this api method in ...

Restricting enum type to only one member

enum Value { First, Second, } interface Data { value: Value number: number } interface SubData { value: Value.Second } function calculation(input: SubData){ return; } function initiate(){ const input : Data = { numbe ...

Retrieve the targeted row from the table and then employ a function

Here is a datatable that I am working on: http://jsbin.com/OJAnaji/15/edit I initially populate the table with data and display it. Then, I add a new column called "kontrole." data = google.visualization.arrayToDataTable([ ['Name', &apo ...

How can I make the arrows work on a secondary slider with EasySlider1.7?

I finally managed to get 2 sliders working on my page after reading through several other tutorials. However, I am facing an issue with the Prev & Next arrows on the second slider as they don't seem to work properly. I inherited this page from someon ...

Error encountered while attempting to import a Bootstrap JavaScript file in webpack

I am currently working on a Gridsome project (v0.7.23) where I have loaded the Bootstrap framework via npm. In this project, I am using node v14.18.0 through nvm. However, when attempting to import a Bootstrap JS component (specifically 'collapse&apo ...

"Exploring the power of NodeJS with createServer, dealing with

Can instances of global.request potentially collide in this NodeJS scenario? I have a basic web server set up in NodeJS where I am globally exposing the request that is created: http.createServer(function(req, res) { global.request = req; // do ...

What is the best way to retrieve information from a database using JSON with PHP, JQUERY, and

Trying to retrieve data from a MySQL database and pass it to a JavaScript file has been quite a challenge. Despite searching extensively online, the examples I found didn't work in my specific scenario. .html file <!DOCTYPE html PUBLIC '-//W ...

Link a PHP variable to a JavaScript variable

Is there a way to set the value of a JavaScript variable using a PHP variable? $(function(){ $("select[name=myselectlist]").change(function(){ var id = $(this).val(); if(id != 0) { $.post("ajax.php", {"id":id}, func ...

Next.js Content Switching: A Step-by-Step Guide

On my app, I have a main dashboard featuring a sidebar navigation and content container. However, being new to next.js and its routing system, I'm unsure how to update the content when a user navigates using the sidebar. Do I need to create separate p ...

What is the best way to save a JavaScript object or JSON within an HTML element using the HTML5 data attribute?

I have an anchor element and I want to store and retrieve the object within it in this specific format. <a id ="test" data-val="{key1:val1,key1:val1}"> </a> When saved in this manner, fetching it with $("#test").data('val') returns ...

Issues with integrating the jsPDF package into a JavaScript project

I'm struggling to solve this issue. I've been attempting to create a program that can download a pdf from a webpage using the jsPDF npm module. After downloading it, I tried importing it in two different ways: Using the node.js require statemen ...

angular data binding returning the identifier instead of the content

I have been dealing with managed fields retrieved from a web server in the following format: { "fields":{ "relationshipStatus":[ { "fieldId":4, "name":"Committed" }, { "fieldId":2, ...

I made a mistake with my git repository. Should I try to fix it or just start fresh?

After spending months learning web development, I recently completed my first project. Unfortunately, right before deployment, I made a mistake with my backend git tree. I attempted to resolve the issue using suggestions from other resources, but none of ...

Incorporating a CSS Module into a conditional statement

Consider the following HTML structure <div className={ `${style.cell} ${cell === Player.Black ? "black" : cell === Player.White ? "white" : ""}`} key={colIndex}/> Along with the associated CSS styles .cell { ...

Obtain content from a div element using jQuery

Here is a snippet of HTML code that I am working with: <!doctype html> <html> <head> <meta charset="utf-8" /> <title>Demo</title> </head> <body> <script src="jquery.js"></script> <scri ...

AngularJS remove a row from a table disrupts the formatting

Hello! I am attempting to delete rows from a table in Angular. I want the first two rows to have a red background and the rest to have a white background. If I try to delete the last row, it gets deleted but the color remains for the first row only (it sh ...

Invoke Office script from beyond MS Excel WebApp

Within the Excel WebApp on Office 365, users have the ability to incorporate Office Scripts through the "Automate" tab. These scripts utilize JavaScript syntax and can automate Excel functions similar to a VBA macro, specifically designed for the Excel Web ...

Booking.com's embedded content is experiencing display issues

My current project involves adding a booking.com embedded widget. Initially, when accessing the main page, everything works perfectly - the map and booking widget are visible for ordering. However, if you switch views without leaving the page or closing th ...