Can we trust the accuracy of the official type definition for JSON.stringify?

Upon reviewing the official type definition for JSON.stringify, it appears that it states JSON.stringify always returns a string, even when passed undefined.

interface JSON {
  stringify(value: any, /*...*/): undefined;
}

However, executing JSON.stringify(undefined) yields undefined, which contradicts the expected string return value.

console.log(JSON.stringify(undefined))

This discrepancy is also confirmed by the documentation.

It seems that the official type definition may be incorrect. What steps can be taken to address this issue?

Answer №1

The use of the return type string is clearly incorrect.

Introducing Typescript Generics can resolve this issue, which may not have been the case in 2017. Therefore, if you reach out to TS developers to inquire about updating this, here's how it can be accomplished now.

type JSONReturnType<T> =
    T extends undefined ? undefined :
    T extends bigint ? undefined :
    T extends Symbol ? undefined :
    string;

interface JSON {
    /**
     * Converts a JavaScript Object Notation (JSON) string into an object.
     * @param text A valid JSON string.
     * @param reviver A function that transforms the results. This function is called for each member of the object.
     * If a member contains nested objects, the nested objects are transformed before the parent object is.
     */
    parse(text: string, reviver?: (this: any, key: string, value: any) => any): any;
    /**
     * Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
     * @param value A JavaScript value, usually an object or array, to be converted.
     * @param replacer A function that transforms the results.
     * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
     */
    stringify<T>(value: T, replacer?: (this: any, key: string, value: any) => any, space?: string | number): JSONReturnType<T>;
    /**
     * Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
     * @param value A JavaScript value, usually an object or array, to be converted.
     * @param replacer An array of strings and numbers that acts as an approved list for selecting the object properties that will be stringified.
     * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
     */
    stringify<T>(value: T, replacer?: (number | string)[] | null, space?: string | number): JSONReturnType<T>;
}

/**
 * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.
 */
declare var JSON: JSON;

const a = JSON.stringify({});              //=string
const b = JSON.stringify(undefined);       //=undefined
const c = JSON.stringify(Symbol(''));      //=undefined
const d = JSON.stringify(BigInt('10000')); //=undefined

TS Playground

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

Sorting an array of objects in Typescript using a dynamic property name for generics

My goal is to develop a versatile, typed function that can arrange an array of objects by a numerical value housed under a dynamically named property within each object. Here is my current progress: export const sortByNumber = <T, K extends keyof T> ...

When a new array object is added to a nested array in a React Redux reducer, the array in the store is correctly updated but the React component

I am brand new to React and redux. Currently, I have a task where I need to implement workflows with tasks inside them. While I successfully managed to add a new workflow object to the state array, I encountered a problem when trying to add a new task - it ...

Exploring the concept of promises in node.js for recursive functions

I'm attempting to use recursive calls in order to fetch data from redis, halting and returning when the members return null. My data is inserted as shown below: SADD parents.<name> <parent1> <parent2> SADD parents.<parent1> & ...

Achieve validation of numerous variables without the need for a string of if-else

If we have three variables, such as firstName, lastName, and email, how can we check if they are empty or not without using multiple if else blocks? let firstName = "John"; let lastName = "Doe"; let email = "john.doe@example.com"; if (firstName.trim() == ...

Sending JSON data from SignalR back to Knockout ViewModel

I'm struggling with my Knockout and SignalR implementation as a beginner. Although I can display JSON data in a debug element by databinding it to dashboard, I encounter undefined errors when trying more complex databinding. For example, the code sni ...

What is the best way to access form data in React using a React.FormEvent<HTMLFormElement>?

I am looking for a way to retrieve the values entered in a <form> element when a user submits the form. I want to avoid using an onChange listener and storing the values in the state. Is there a different approach I can take? login.tsx ... interfa ...

Generating an image from a byte array using Jax-RS

I need help displaying an image when a user accesses the URL http://localhost:8080/app/profile/getImage/5315d33284aec8c202eef15a. The image to be displayed corresponds to the ID 5315d33284aec8c202eef15a. This is my service implementation: @GET @Path( ...

Uploading Files through Reactive Forms in Angular

I tried following a tutorial on integrating file upload functionality into my reactive form, which can be found at the following link: . However, I've encountered an issue where I'm getting an error message stating "this.onChange is not a functio ...

Clicking a link will trigger a page refresh and the loading of a new div

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> $(window).load(function () { var divs = $( #add_new, #details"); $("li a").click(function () { ...

Attributes of the host element in Angular 1.5 components

I am seeking a way to customize attributes on the host element for Angular 1.5 components. What is the purpose? I would like to assign a class to a component in order to apply specific styles. For example, if the parent component has display: flex set, ...

Stop hyperlinks from automatically opening in a new tab or window

I'm having trouble with my website links opening in new tabs. Even after changing the attributes to _self, it still doesn't work. Can someone please review my code below and provide a solution? Feel free to ask for more clarification if needed. ...

Attempting to retrieve data from a JSON file according to the choice made by the user in a dropdown menu

My goal is to create a user interface where users can select options from a drop-down list and receive corresponding output based on their selection. The drop-down list options are populated using data from a JSON file, and the desired output is derived fr ...

What is the best way to set a Firestore data field as a variable?

I am working with a firebase collection named 'messages', where I add documents as follows: this.afs.collection('messages').add({ 'qn': message, 'student': this.student, 'upvotes': this.upvote }); The upv ...

Working with SASS imports in an isomorphic React app: best practices

Currently, my React app is set up with SSR support as follows: React app Express server that compiles the React app using webpack Using babel-node to run the Express app with ES6 features Everything works fine until I added CSS modules to the React app, ...

Problems with form functionality in React component using Material UI

Trying to set up a signup form for a web-app and encountering some issues. Using hooks in a function to render the signup page, which is routed from the login page. Currently, everything works fine when returning HTML directly from the function (signup), ...

Incorporate npm libraries into vanilla JavaScript for HTML pages

Attempting to incorporate an npm package into plain JS/HTML served using Python and Flask. <script type="module"> import { configureChains, createClient } from "./node_modules/@wagmi/core"; import { bsc } from "./nod ...

Issue with React Js: Text Sphere not appearing on page reload

Currently immersed in a react.js environment and eager to incorporate this impressive animated text sphere. Utilizing the TagCloud package for rendering assistance, however, encountered an issue where the text sphere would only display once and disappear u ...

Learn the process of downloading a pdf file with vuejs and bootstrap-vue

Having trouble uploading a PDF file to my browser and then downloading it afterwards. The upload is fine, but the download isn't working. This is how I am uploading: <b-form-file v-model="form.file" :state="Boolean(form.file)" placeholder="Choose ...

Creating a JSON serialization tool

When considering developing a serializer for a language like ABAP where there isn't currently one available, what are the potential challenges and efforts required? Is it simply a matter of creating a text equivalent of an ABAP serializer or would mor ...

Retrieve the row based on the user_id and also include any rows that have the same event_id as that entry

I have a table with the following structure: _______________________________ | event_id | user_id | username | |-------------------------------| | 30 | 1 | user1 | | 30 | 2 | user2 | | 30 | 3 | user3 | | 31 ...