Issue encountered when employing the spread operator on objects containing optional properties

To transform initial data into functional data, each with its own type, I need to address the optional names in the initial data. When converting to working data, I assign a default value of '__unknown__' for empty names.

Check out this code snippet:

/* @flow */

type NAME_OPTIONAL = {
  name?: string
}

type NAME_MANDATORY = {
  name: string
}

type INITIAL = {
  source: string,
  data: NAME_OPTIONAL[] // <-- Here the names are OPTIONAL.
}

type WORKING = {
  source: string,
  data: NAME_MANDATORY[] // <-- Here the name are MANDATORY.
}

// We have some initial data.
const initial: INITIAL = {
  source: 'some.server.com',
  data: [{ name: 'Adam' }, { name: undefined }]
}

// And we want to turn initial data into working data.
const workingData = initial.data.map((i) => {
  return { 
    name: i.name || '__unknown__'
  }
});

// This is OK:
const working1: WORKING = {
  source: initial.source, 
  data: workingData
}

// This is NOT OK:
const working2: WORKING = {
  ...initial,
  data: workingData
}

In the above example, initializing working1 is successful, but trying to initialize working2 using the object spread operator triggers a flowtype error:

4:  name?: string
            ^ undefined. This type is incompatible with
8:  name: string
           ^ string

I'm puzzled by how the spread operator can cause this issue. Any insights on this would be appreciated. Thank you.

Check out the "Working" example on https://flowtype.org/try/... here.

Answer №1

There have been numerous issues reported regarding the spread operator on GitHub. Your situation appears to be similar to this particular case.

It seems like a solution may not be available until the problem is resolved, but one workaround could be replacing the operator with Object.assign:

const working2: WORKING = Object.assign({}, initial, { data: workingData })

If that doesn't work, you can try adding an annotation above the line:

// $FlowIssue
const working2: WORKING = Object.assign({}, initial, { data: workingData })

Alternatively, you can also do this:

// $FlowIssue
const working2: WORKING = {
  ...initial,
  data: workingData
}

Afterwards, make sure to include this setting in your .flowconfig:

[options]
suppress_comment=.*\\$FlowIssue

By doing this, you should be able to suppress the error.

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 there a way to find out the ultimate destination of a shortened URL without actually opening the webpage?

I am trying to implement a feature where I can click on links within email messages and have the full link displayed in a separate pane using jQuery. However, I am facing some challenges with this implementation. My plan is to use AJAX to call a PHP scrip ...

What is the best way to submit updated data from an Angular form?

Currently, I have a situation where multiple forms are connected to a backend service for storing data. My query is whether there exists a typical angular method to identify which properties of the model have been altered and only send those in the POST r ...

Are Ajax Caching and Proper Format Being Employed?

Can you help me with a JavaScript event that I have to call in this way: function addEvent(date, resId) { $("#appPlaceholder").load("/Schedule/Add?date=" + date.format()+"&resourceId="+resId, function () { $('#event ...

Easily update the title of a webpage in the browser's history using JavaScript

Is it feasible to use JavaScript to modify the title of a page in the browser history even after the page has finished loading? This functionality should work consistently across different browsers, including those that do not support the HTML5 History API ...

Experiencing unexpected output from Angular model class method

I have developed a user-friendly Invoicing & Inventory management application that showcases a list of invoices for each customer. However, there seems to be an issue with the calculation of the Grand Total function, which I am struggling to rectify due to ...

With TypeScript, you have the flexibility to specify any data type in the generic types when using the axios.get method

axios.get('/api') When working with TypeScript as shown above, it is important to designate types for better clarity. This allows us to reference the type definition of axios, like so: (method) AxiosInstance.get<any, AxiosResponse<any> ...

Utilizing numerous instances of setInterval

I've created a jsFiddle which can be found here: http://jsfiddle.net/dztGA/22/ Main Objective: My aim is to have two independent timers on the same page that can be stopped and restarted either by hovering or manually. The Issue: The problem illustr ...

Executing a Function Prior to onClick Event of a Link Element in Next.js

While working on a slider/carousel, I encountered an issue. Each photo in the slider should be draggable back and forth, with a click taking the user to a product page. I am using next.js with react-flickity-component for this purpose. Please note that thi ...

Utilizing ng-repeat to loop through a div element that consists of various nested tags

I need to display multiple tabs, with each tab having a table where the values are populated from a database. The number of tabs is dynamic and fetched from another page of the application. All tables have the same structure but different values. How can I ...

Trouble with AngularJS: Updates not reflecting when adding new items to an Array

I am facing a persistent issue that I have been unable to resolve, despite researching similar problems on StackOverflow. My current project involves building an application with the MEAN stack. However, I am encountering difficulties when trying to dynam ...

I want to create a feature where a video will automatically play when a user clicks on a specific item in a list using Angular

Currently, I'm working on a project that involves displaying a list of videos and allowing users to play them in their browser upon clicking. The technology stack being used is Angular 2. Below is the HTML code snippet for achieving this functionalit ...

Top method for utilizing jQuery to locate, sift through, and implement CSS classes

Let's consider the following scenario: <span class="foo">7</span> <span class="foo">2</span> <span class="foo">9</span> We want to assign a CSS class of 'highest' to 'span.foo' with value great ...

excessive memory usage in a simple react-native application

My experience with creating my first react native app has been more challenging than I initially expected. I'm having trouble understanding what I might be doing wrong. Initially, the app is simple, fetching data through Redux. componentWillMount() ...

Cross-Origin Resource Sharing (CORS) for HTML

Here is a code snippet I found on http://jakearchibald.com/scratch/alphavid/ $("#video").append('<video id="movie" style="display:none" autobuffer><source id="srcMp4" src="https://host-away-from-host.com/file.mp4" type=\'video/mp4; ...

Can HTML be transferred between browser tabs using Angular?

I'm in the process of developing a unique Angular (v17) application that allows users to drag and drop HTML elements, even across multiple browser tabs. I am inspired by the capabilities demonstrated by neo.mjs, as shown in this demo: https://www.yout ...

JavaScript's native innerHTML function is unable to access the content generated by Vue

I have been struggling with extracting the content from a specific div element in my HTML code. <div id="output" ref="output_data"> <h1>{{ information }}</h1> </div> I attempted to retrieve the contents using ...

What is the best way to submit form data along with an image using Angular?

Recently, I built an application where users can submit form data along with an uploaded image. Since I am new to Angular, I am facing some challenges in merging the user-submitted data model and the image upload using the FormData method. Can anyone guide ...

Tips for maintaining the full width/height ratio of a child image when covering a fixed size container

I have a square container with dimensions of 300x300 and an <img src="" /> image inside. My goal is for the image to cover the entire container while maintaining its width/height ratio. If the image's width is smaller than its height ...

"Converting Text from a Streamed XML-Like File into CSV: A Step-by-Step Guide

I have log files that contain C++ namespace artifacts (indicated by the double colons ::) and XML content embedded within them. After loading and displaying the logs in a browser application, the content has been separated from the Unix timestamps like so: ...

The autoplay feature for YouTube videos is not functioning on Chrome when viewed on an iPhone

if($('.explore-video-btn').length > 0) { var video_id = youtube_parser($('.explore-video-btn').attr('data-video-url')); } var tag = document.createElement('script'); tag.src = "https://www.youtube.com/iframe_api" ...