Pesquisa de site

javascript - A definição de tipo oficial para JSON.stringify está errada?


Eu vejo na definição de tipo oficial para JSON.stringify que ele sempre retorna uma string, mesmo quando é passado undefined

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

No entanto, JSON.stringify(undefined) é undefined e, portanto, não é uma string

console.log(JSON.stringify(undefined))

conforme confirmado pelos documentos

Então, a definição de tipo oficial parece estar errada. O que eu posso fazer a respeito?

Resposta #1

O tipo de retorno sendo string é obviamente errado.

Generics do TypeScript vão resolver esse problema, em 2017 isso pode não ter sido o caso. Então, se você entrar em contato com os desenvolvedores do TS para ver se isso pode ser atualizado, é assim que pode ser feito agora.

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

Playground TS

Artigos relacionados