Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript array map with JSON.stringify produces error

Tags:

typescript

In Typescript, this snippet:

[].map(JSON.stringify);

Is producing this error:

Argument of type '{ (value: any, replacer?: ((key: string, value: any) => any) | undefined, space?: string | number | undefined): string; (value: any, replacer?: (string | number)[] | null | undefined, space?: string | ... 1 more ... | undefined): string; }' is not assignable to parameter of type '(value: never, index: number, array: never[]) => string'. Types of parameters 'replacer' and 'index' are incompatible. Type 'number' is not assignable to type '((key: string, value: any) => any) | undefined'.

Which I don't think it should.

To me this looks like a Typescript bug but before I file an issue in GitHub can you check if I'm doing something wrong?

Typescript version: 3.0.3

like image 428
Guy Avatar asked Aug 04 '26 07:08

Guy


2 Answers

The signature of JSON.stringify and the Array.mapare not compatible due to the second parameter:

interface JSON {
    /**
      * 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(value: any, replacer?: (key: string, value: any) => any, space?: string | number): string;
}

interface Array<U> {
    /**
      * Calls a defined callback function on each element of an array, and returns an array that contains the results.
      * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
      * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
      */
    map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];
}

Here you can see that stringify does not match callbackfn because the second arguments do not match.

But you can absolutely do [].map(i => JSON.stringify(i))

like image 164
Clément Prévost Avatar answered Aug 06 '26 03:08

Clément Prévost


That's not a bug, it's clearly telling you that the type for the second argument of JSON.stringify (which is the replacer function), doesn't match the expected second argument of type number (which is the index) of the map function.

like image 39
cyr_x Avatar answered Aug 06 '26 04:08

cyr_x