Steps to create a JSON-compatible parameter and prevent the occurrence of the error message "Missing index signature":

My function is defined as:

export function useSubmitHandler(url: string, data: Json): [FormEventHandler<HTMLFormElement>, boolean] {}

The definition of Json is as follows:

type JsonPrimitive = string | number | boolean | null | undefined
interface JsonMap extends Record<string, JsonPrimitive | JsonArray | JsonMap> {}
interface JsonArray extends Array<JsonPrimitive | JsonArray | JsonMap> {}
export type Json = JsonPrimitive | JsonMap | JsonArray

An error occurs when trying to pass an arbitrary interface to the function:

TS2345: Argument of type 'Fee' is not assignable to parameter of type 'Json'.   
Type 'Fee' is not assignable to type 'JsonMap'.     
Index signature is missing in type 'Fee'

https://i.sstatic.net/yOUGC.png

However, if the object is spread like {...store.data} then the error disappears.

What modifications are needed to the useSubmitHandler type to accept any JSON stringifyable object?

The structure of Fee is:

interface Fee {
    id: number|null;
    name: string;
    type: string;
    amount: string;
    default: number;
    company_id: number;
    deleted_at?: any;
    active: number;
    fee_or_discount: string;
}

The goal is for this solution to be compatible with any type.

Answer №1

Option 1: Modify the Json type definition

type JsonPrimitive = string | number | boolean | null;
type JsonMap = {
    [key: string]: JsonPrimitive | JsonMap | JsonArray;
}
type JsonArray = Array<JsonPrimitive | JsonMap | JsonArray>;
type Json = JsonPrimitive | JsonMap | JsonArray;

Option 2: Extend the Fee interface with an index signature

interface Fee {
    [property: string]: any;
    id: number|null;
    name: string;
    type: string;
    amount: string;
    default: number;
    company_id: number;
    deleted_at?: any;
    active: number;
    fee_or_discount: string;
}

Option 3: Use inline type assertion for the index signature, like this:

useSubmitHandler(Router.route('fees.store')!, store.data as {[property: string]: any})

Check out

TypeScript GitHub issue Suggesting a new basic type for JSON #1897

Answer №2

To address this issue, one approach is to encapsulate store.data within a function that applies an index signature.

const indexedData = <T extends {}>(obj: T): T & {[key: string]: never} => obj;

This function essentially returns the original object but augments it with additional TypeScript information. It preserves all existing values of type T, while introducing an index signature {[key: string]: never} to indicate to TypeScript that any keys not present in the type must be undefined.

You can invoke the handler like so:

runHandler(url, indexedData(store.data))

Playground Link

Alternatively, you could redefine Json without the index signature provided by using Record. However, this may require expanding the allowable properties which might not be ideal.

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

Creating a JSON schema from a JAXB annotated class: A step-by-step guide

I have a class entity that looks like this: @XmlRootElement public class ImageSuffix { @XmlAttribute private boolean canRead; @XmlAttribute private boolean canWrite; @XmlValue; private String value; } And for JSON generation, I ...

The MongoDB operator that checks for multiple values within a specified field

I created a table with the following values: [ { id: 1, name: "abc" }, { id: 2, name: "lmn" }, { id: 3, name: "xyz" } ] My query includes $in as follows: { id: { $in: [ 2, 3, 1 ] } } I am hoping for the output to be in this or ...

Using HTML5 to display the {{data}} extracted from a JSON file right in the center of the text

Can someone help me with a question about working with html and angular5? <span [innerHTML]="'client.acceptance.explanation'| translate"></span> <span><b>{{data}}</b></span> I have text stored in a json file ...

What is the best way to store a collection of objects generated from an AJAX request that retrieves information from a JSON file using JavaScript?

I have successfully retrieved my JSON objects using the code snippet below. After logging the variable "value2", I can confirm that the values are being displayed in my console. However, I am encountering an issue where my "arraytest" remains empty even af ...

typescriptIs there a more efficient approach to typing optional values without a default value in

In my React application with TypeScript, I am using the following code to provide typed props: type ScheduleBoxContentProps = { desc: ReactNode, lottie: LottieProps, } & Partial<{className: string}>; I want the className prop to be optional ...

Modifying tooltip format in React ApexChart from dots to commas

I am in the process of creating an app targeted towards German users, who traditionally use commas (20,00) instead of dots (20.00) for numbers. I am using react-apexcharts and struggling to figure out how to replace the dots with commas in both my chart an ...

Show values in array that include a certain keyword

Currently, I am developing a search function for my json decoded results The code snippet that I have written is as follows: <?php foreach($soeg_decoded as $key => $val){ $value = $val["Value"]; $seotitle = $val["SEOTitle"]; $text = $va ...

Fake AxiosInstance. In need of obtaining response in a single test

In my api.ts file import axios from 'axios' export const api = axios.create({ baseURL: 'http://localhost:3333/', }) Within my react-page.spec.tsx file: import React from 'react' import '@testing-library/jest-dom&apo ...

What is the best way to reference typescript files without using absolute paths?

As typescript does not seem to have built-in support for absolute path references (according to this GitHub issue), it becomes difficult to organize and maintain my file references. With TypeScript files scattered across various locations in my folder stru ...

Employing [style.something.px]="2" in Angular to specify the thickness of the border

Presently, I am setting the width of the element using this code format: <div [style.width.px]="size" [style.height.px]="size"></div> What I am aiming for is to utilize a comparable format but to define the border-width css attribute, such as ...

Having trouble with mapping a localStorage variable containing an Array of Objects, which results in the item disappearing

In my localStorage, I have an array called product_categories that contains various objects, each consisting of a string and a nested array of objects representing products belonging to each category. Despite seeking help from Appery's support team o ...

Unraveling the Mystery of the Undefined Parameter in Angular Observables

I am facing an issue with the Observable parameter in my code. I have a consultService that contains the functions consult() and response as a parameter. The function sendConsultRequest() is called before using the response parameter. Although the sendCons ...

Query a SQL database using PHP and retrieve data from array fields

I am working on a website that involves using ajax requests to retrieve data from a mySQL database. For the sake of simplicity, let's consider the following database structure : Table OBJECT ID_OBJECT (int) NAME_OBJECT (varchar) Table IMAGE ...

Convert several JSON files into an HTML table using PHP - an abundance of rows

Currently, I am running a python script that generates JSON files and saves them to a specific directory. My goal is to extract data from these JSON files and display it in an HTML table. While everything seems to be functioning correctly, I am encounter ...

Implement dynamic options in dropdown menu using JQuery AJAX call to retrieve data in JSON format

I am currently diving into the world of JQuery and exploring AJAX requests. Sample Code: Javascript: success: function(json) { console.log(json); var $el = $("#system"); $el.empty(); // removing old options $el.append($( ...

Using object bracket notation in TypeScript to retrieve values from props with the help of string interpolation

I encountered an issue in my code while attempting to utilize a variable within my TSX component. This problem arises due to the dynamic props being passed into the component, which are always a string that matches one of four keys in the "characters" obje ...

Identifying the Correct Data Type of Objects in JSON Using Objective-C

I am facing an issue with my JSON service that deals with registering new users. In case of errors such as "Email in use" or "Taken username," the service returns error codes separated by the "|" character within a string format. However, when the registra ...

When transferring information from the UI controller to Javascript, there is a risk of losing certain data points in the process

My UI controller is returning data with two objects of the same type, each representing a certain entity. Both objects have values assigned to them, as shown when fully expanded. https://i.sstatic.net/Txhwh.png However, when inspecting the JavaScript, th ...

Change object values to capital letters

Upon retrieving myObject with JSON.stringify, I am now looking to convert all the values (excluding keys) to uppercase. In TypeScript, what would be the best way to accomplish this? myObj = { "name":"John", "age":30, "cars": [ { "name":"Ford", ...

Issue with Discord.js (14.1) - Message Handling Unresponsive

After developing a sizable Discord Bot in Python, I decided to expand my skills and start learning JS. Despite thoroughly studying the documentation and comparing with my original Python Bot regarding intents, I am facing difficulties getting the message ...