The data type 'string | number | boolean' cannot be assigned to type 'undefined'. Specifically, the type 'string' is incompatible with type 'undefined'. Error code: ts(2322)

When attempting to create a partial object with specific fields from a full object that meet certain criteria, I encountered a TypeScript error message. To better explain this issue, I designed a test module to showcase the concept/problem without using actual code.

type FullObject = {
  id: number
  name: string
  active: boolean
}

type PartialObject = Partial<FullObject>

const myFullObj: FullObject = {
  id: 1,
  name: 'First Object',
  active: true,
}

const myPartialObj: PartialObject = {}

let k: keyof PartialObject

for (k in myFullObj) {
  if (myFullObj[k] !== undefined) myPartialObj[k] = myFullObj[k] // Error occurs here
  if (k === 'name') myPartialObj[k] = myFullObj[k] // No error here
}

The error mentioned above only arises within the first "if" statement. Through research and experimentation, I found a workaround by initializing the partial object as the full object and then removing properties that do not align with the criteria. However, I view this solution as inefficient and would prefer to directly create a partial object consisting of properties that satisfy the criteria.

Answer №1

I devised a solution that clearly demonstrates my goal: if a certain condition is met with a property of the source object, then copy that property to the partial destination object. In this scenario, I am using "not undefined" as the condition. The actual condition in the code is more intricate.

type FullObject = {
  id: number
  name: string
  active: boolean
}

type PartialObject = Partial<FullObject>

const myFullObj: FullObject = {
  id: 1,
  name: 'First Object',
  active: true,
}

let myPartialObj: PartialObject = {}

let k: keyof PartialObject

for (k in myFullObj) {
  if (myFullObj[k] !== undefined) myPartialObj = { ...myPartialObj, ...Object.fromEntries([[k, myFullObj[k]]]) }
}
console.log(JSON.stringify(myPartialObj, null, '  '))

It appears that there may be a more efficient way to achieve this. Nonetheless, the example effectively showcases the intended functionality.

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

steps to retrieve JSON object using Angular service

In the login.js file, I have a module with a method called loginUser structured like this: ...function loginUser(){ var user={ email:loginVM.Email, password:loginVM.pwd }; console.log(user); loginService.login ...

The functionality of Vue is acting up with the HTML, unexpectedly refreshing when a button is clicked

I am currently experiencing an issue with my Vue application. When I click the button, it clears the input field (which it shouldn't) and doesn't perform any other actions. The variables "codigo" and "payload" do not display anything on the scree ...

TypeScript focuses on checking the type of variables rather than their instance

Is there a way to pass a type (not an instance) as a parameter, with the condition that the type must be an extension of a specific base type? For example abstract class Shape { } class Circle extends Shape { } class Rectangle extends Shape { } class ...

What is the accurate user agent for Windows Phone?

Can someone explain why PHP and JavaScript produce different user agents? Which one is considered the accurate user agent? PHP User Agent Output: <?php print_r($_SERVER['HTTP_USER_AGENT']); ?> User Agent: Mozilla/5.0 (Mobile; Windows Ph ...

Experiencing a problem with XAMPP? Changes made to the code are not reflected after saving

Recently, I've encountered a strange issue with my XAMPP test server while working on a game project. Everything was running smoothly until I noticed that when I make changes to certain files in Notepad++ and save them, the updates are not being refle ...

Tally up the values of selected checkboxes

  I'm in search of a method to tally up data-values associated with checkboxes. In the example provided below, selecting locations from the checkboxes results in the calculation of primary values, which are displayed in the green box. I also need to ...

What is the best way to transfer a variable from a node server to a javascript client when the page is first

My web application is mainly static, but I need to dynamically send the user's username if they are logged in and the room name they specify in the URL to the client-side JavaScript upon page load. Finding a simple solution has been challenging for me ...

Attempting to modify Namecheap's custom DNS field through Python Selenium

I am facing an issue while attempting to modify DNS settings for domains in Namecheap using Python Selenium Below is the HTML code: <select class="dashed-select add-margin ng-untouched ng-valid select2-offscreen ng-dirty ng-valid-parse" ng-change="nam ...

The object's value may be 'undefined' after utilizing a switch case to ensure it is not undefined

Before I encountered the error Object is possibly 'undefined'.ts(2532) at testObject["x"], I had used case "x" in testObject. Why did this happen? Should I create my own type guard for it? interface TestObject { a?: number; ...

What is the process of invoking the POST method in express js?

I've been diving into REST API and recently set up a POST method, but I can't seem to get it to work properly. The GET method is running smoothly in Postman, but the POST method is failing. Can someone lend a hand in figuring out where I'm g ...

Node.js server for Cross-Origin Resource Sharing

I'm brand new to Node.js and I'm trying to run some example code, but I keep encountering CORS issues. Server.js var http = require('http'); var io = require('socket.io'); server = http.createServer(function(req, r ...

Vue app hosted on Firebase displays a blank page when user logs in

After deploying my Vue2 project to Firebase hosting server, visitors are required to log in to access the other pages. The issue is that once a user successfully logs in, they are redirected to the next page but it appears blank. Below is what the firebas ...

A guide on transforming HTML into a variable using JavaScript

Having trouble converting HTML to a JavaScript variable. This is my HTML code: <div onclick="openfullanswer('2','Discription part','This is the code part');"> I want to create this HTML code dynamically, but I&apo ...

Exploring the concepts of closure and scope

It seems that the function inResult always returns false and the loop is not being executed, probably due to a lack of understanding of closures. However, I can confirm that the result variable contains the correct properties. function hasId() {return ...

How can an array be generated functionally using properties from an array of objects?

Here's the current implementation that is functioning as expected: let newList: any[] = []; for (let stuff of this.Stuff) { newList = newList.concat(stuff.food); } The "Stuff" array consists of objects where each ...

Create a union type by utilizing indices of an array type

For instance: type BasicTheme = { name: 'basic'; colors: [string, string]; }; type AdvancedTheme = { name: 'advanced'; colors: [string, string, string, string]; }; type MainColor = ???; // 'main-1' | 'main-2&apo ...

Django plugin designed for showing a real-time feed of messages - powered by Dajax or Jquery?

Currently, I am attempting to set up a section in my Django application where updates or messages from the server can be displayed once specific tasks are done. I had initially looked into using a plugin that utilizes Dajax / Jquery for this feature, but ...

What sets the target property of the mousewheel event apart from other events like click, mousedown, and touchstart?

The mousewheel event's target property reveals the DOM element currently being hovered over when using the mousewheel or gesture-capable touchpad. In my experience (specifically in Safari 6, I will verify this in other browsers later), the target ret ...

jquery survey quiz

Currently, I am attempting to develop a jQuery questionnaire, but my limited knowledge in the area is proving to be quite inadequate. So far, here is what I have: Upon clicking on "Questions," a pop-up window will appear with two questions. My goal is t ...

Inserting duplicate rows from CSV using JavaScript

Currently, I am utilizing Papaparse to sum up rows with duplicate SKUs in my CSV file. I'm striving to achieve this task without the use of additional JS libraries such as D3. Here is a snippet of how my CSV data is structured: SKU,Daily total,Weekly ...