使用 JSON.stringify 的 Typescript 数组映射会产生错误

Guy*_*Guy 2 typescript

在 Typescript 中,这个片段:

[].map(JSON.stringify);
Run Code Online (Sandbox Code Playgroud)

正在产生此错误:

类型参数 '{ (value: any, Replacer?: ((key: string, value: any) => any) | undefined, space?: string | number | undefined): string; (值:任意,替换者?:(字符串 | 数字)[] | null | 未定义,空格?:字符串 | ... 1 更多 ... | 未定义): 字符串;}' 不可分配给类型为“(value: never, index: number, array: never[]) => string”的参数。参数“replacer”和“index”的类型不兼容。类型“number”不可分配给类型“((key: string, value: any) => any) |” 不明确的'。

我认为不应该。

对我来说,这看起来像是一个 Typescript bug,但在我在 GitHub 上提交问题之前,你能检查一下我是否做错了什么吗?

打字稿版本:3.0.3

Clé*_*ost 6

由于第二个参数,JSON.stringify和 的签名不兼容:Array.map

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[];
}
Run Code Online (Sandbox Code Playgroud)

在这里您可以看到stringify不匹配callbackfn,因为第二个参数不匹配。

但你绝对可以做到[].map(i => JSON.stringify(i))