Tips for universally updating the FormData TypeScript interface within React Native applications

While attempting a simple append with FormData in React Native like the following...

const formData = new FormData();
formData.append('image-data', {
  uri: '/awesome-chat-app/ImagePicker/abb9-a435046e971c.jpg',
  name: 'image001.jpg',
  type: 'image/jpeg',
});


An issue arises when TypeScript complains...

Error: Argument of type '{ uri: any; name: string; type: string; }' is not assignable to parameter of type 'string | Blob'. Object literal may only specify known properties, and 'uri' does not exist in type 'Blob'.ts(2345)


To solve this problem, I found a way to redefine FormData as shown below... (hat tip)

interface FormDataValue {
  uri: string;
  name: string;
  type: string;
}

interface FormData {
  append(name: string, value: string | Blob | FormDataValue, fileName?: string): void;
  delete(name: string): void;
  get(name: string): FormDataEntryValue | null;
  getAll(name: string): FormDataEntryValue[];
  has(name: string): boolean;
  set(name: string, value: string | Blob | FormDataValue, fileName?: string): void;
}

declare let FormData: {
  prototype: FormData;
  new (form?: HTMLFormElement): FormData;
};

interface FormData {
  entries(): IterableIterator<[string, string | File]>;
  keys(): IterableIterator<string>;
  values(): IterableIterator<string | File>;
  [Symbol.iterator](): IterableIterator<string | File>;
}


Implementing this solution worked perfectly within the file where the append operation was performed.

Now, the question remains - how can we define this globally in the project so that it overrides all uses of FormData?

Answer №1

To customize the FormData interface from lib.dom.d.ts, utilize a global ambient module along with interface merging:

declare global {
  interface FormDataValue {
    uri: string;
    name: string;
    type: string;
  }

  interface FormData {
    append(name: string, value: FormDataValue, fileName?: string): void;
    set(name: string, value: FormDataValue, fileName?: string): void;
  }
}

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

Firestore query is returning empty results upon page initialization, but provides data upon subsequent re-renders in React Native

ISSUE I'm encountering an issue where I am unable to fetch documents from a Firestore collection when the page loads. Despite executing the query multiple times during loading, it does not return any results. However, if I trigger the query by changi ...

Curious about the method of refining a list based on another list?

As a beginner in coding, I am facing a challenge in my code.org assignment. I need to filter songs by a specific artist from a dataset. Currently, I have code that randomly selects an artist, but I am struggling to filter out songs by that artist from the ...

"Calculating the time difference between a specified time and the current time using Typescript can be achieved by

Incorporating Angular 7, my goal is to exhibit elements in the component HTML only if a certain condition is met: namely, if the provided time is ahead of the current time. After several attempts, I came up with the following logic: checkTimeDifference( ...

Struggling to create a SVG Line with DOM Manipulation in Typescript

I'm having trouble adding an SVG element to my div using the appendChild function in TypeScript. I want to add a line inside the SVG, but for some reason, I can't see the line output on my browser. There are no errors showing up either. Please he ...

Having trouble parsing an array of JSON objects

My brain is struggling to understand how to handle JSON objects properly. Below is the JavaScript code causing me stress: function get_cities(id) { $('#def').hide(); $('#cities').html(''); $.get('/emprego/i ...

A guide on extracting certain fields and values from a JSON structure

I received a JSON output from the response body that contains various details about a contract. My goal is to extract only two specific pieces of information: "contractId" "contractStatus" To achieve this, I'm utilizing JavaScri ...

Personalize the marker design within the Wikitude SDK using JavaScript

Currently, I am developing an augmented reality view in Android using the wikitude-sdk. As part of the project, I am displaying markers on the screen and now I am looking to customize the marker view using the AR.HtmlDrawable method offered by the ...

A guide on personalizing HTML for Django forms

I have implemented an HTML template on my website and need to capture information for my Django backend. Specifically, I am trying to extract the email address from this section of code: <input type="text" placeholder="Email" value="" style="height: 30 ...

I am seeking guidance for developing my own messaging platform, similar to Discord, using Typescript

Allow me to simplify this for you. This piece of code outlines TypeScript interfaces and namespaces for a WebSocket API that is commonly used in a chat or messaging system. It seems to define the format of messages being exchanged between a client and ser ...

Is there a way to incorporate timeouts when waiting for a response in Axios using Typescript?

Can someone assist me in adjusting my approach to waiting for an axios response? I'm currently sending a request to a WebService and need to wait for the response before capturing the return and calling another method. I attempted to utilize async/aw ...

Vue js for filtering and replacing prohibited words

For this scenario, our objective is to screen the words in our input: <input type="text" class="form-control" placeholder="Write something..." v-model="todoInput""> Below are the restricted words that we aim to substitute in the input "restrict ...

Activate a Bootstrap tab using turbolinks dynamically

After loading the page, I am attempting to open a Bootstrap 4 tab. It works when I refresh the page, but if I navigate within the site, it gives me a query selector empty error. This code is a port of the solution mentioned in this tutorial, as I am using ...

Issue with jQuery.off when using a dynamic function name

I am currently implementing a modular pattern for writing my JavaScript code and it has been an enjoyable experience! However, I have encountered a challenging situation. My Namespace structure looks like this: var settings, handlers, objects, Namespace ...

Tips for sharing the scope using module.exports

Within handler.js, I have exported 2 functions: one for initialize() and the other for handle(). The initialize function is used to dynamically load the handler based on the application settings. I have a shared variable called var handler outside the modu ...

Detecting typescript syntax errors: checking for if statements and calling class methods

When I'm debugging, I've noticed that the silly mistakes I make are often the hardest to spot. For example: if (id = userId) {..} And in class methods: let result = myClass.doThis; Oddly enough, VSCode doesn't catch these errors during co ...

Connecting ViewChild to several elements

I have implemented a feature where I am displaying tabular data in DataTable for Angular. Within this, there is a button that triggers a click event. Upon clicking the button, a slide menu is displayed, which then triggers a modal open. To achieve this fun ...

Exploring AngularJS: Effortlessly Retrieving Object Values

HTML: <div ng-app = "" ng-controller = "personController"> <p>Persoon: <select ng-model="persoon"> <option ng-repeat="person in persons">{{person.FirstName}} {{person.FamilyName}}</option> & ...

TypeScript fails to recognize that the filtered array consists entirely of one type when using a type guard

I recently stumbled upon this code snippet in a coding playground where TypeScript is used: export interface Page { heading: string; component: string; path: string; } export type RouteOnly = Pick<Page, 'heading' | 'path'> ...

What could be causing my chosen value to remain unchanged after being copied from a controller?

I am struggling with controlling a <select> element using both ng-model and ng-options: <select ng-model="user.option" ng-options="value.label for (key, value) in data.options"> <option value="">Select value</option> ...

What could be causing my for loop to not function properly within the ngOnInit lifecycle hook?

I am attempting to create a nested loop structure in order to access an array that is inside an object within an array of objects, and then store this data into a new array. My issue arises as the first loop executes successfully but the second one does no ...