TypeScript重载函数工厂定义及JSON.stringify包装函数的类型问题
JSON.stringify with Overloads Let's break down why you're seeing that TypeScript error and how to fix it.
The Root Cause
Your myStringify function is trying to accept both types of replacer parameters from the original stringify overloads in a single signature. TypeScript can't resolve which overload of stringify to use when you pass a union type like ((key: string, value: any) => any) | (number | string)[] | null as the replacer—it doesn't know if it should match the "function replacer" overload or the "array replacer" overload.
Solution 1: Mirror the Original Overloads
The cleanest fix is to give myStringify the same overload signatures as the original stringify function. This lets TypeScript correctly map each call signature to the right overload of the underlying stringify:
// Mirror the original overloads for stringify declare function stringify( value: any, replacer?: (key: string, value: any) => any, space?: string | number ): string; declare function stringify( value: any, replacer?: (number | string)[] | null, space?: string | number ): string; // Add overloads for myStringify first function myStringify( data: any, replacer?: (key: string, value: any) => any, space?: string | number ): string; function myStringify( data: any, replacer?: (number | string)[] | null, space?: string | number ): string; // Then implement the function with a compatible signature function myStringify( data: any, replacer?: ((key: string, value: any) => any) | (number | string)[] | null, space?: string | number ) { return stringify(data, replacer, space); // No more error! }
Solution 2: Use Type Guards in the Implementation
If you don't want to duplicate overload signatures, you can use type guards inside myStringify to explicitly check what type replacer is, then call stringify with the correct parameter type:
declare function stringify( value: any, replacer?: (key: string, value: any) => any, space?: string | number ): string; declare function stringify( value: any, replacer?: (number | string)[] | null, space?: string | number ): string; function myStringify( data: any, replacer?: ((key: string, value: any) => any) | (number | string)[] | null, space?: string | number ) { if (typeof replacer === 'function') { return stringify(data, replacer, space); // Matches function overload } else { return stringify(data, replacer, space); // Matches array/null overload } }
Quick Note on Parameter Types
I adjusted data: object to data: any in the examples because the native stringify accepts any value (not just objects—like strings, numbers, booleans, etc.). If you specifically want myStringify to only accept objects, you can keep data: object, but just be aware it's a stricter constraint than the native function.
内容的提问来源于stack exchange,提问作者Zheeeng

