Skip to content

JSON.stringify can return undefined #29962

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/harness/fourslash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1518,7 +1518,7 @@ Actual: ${stringify(fullActual)}`);

public printCurrentParameterHelp() {
const help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition, /*options*/ undefined);
Harness.IO.log(stringify(help));
Harness.IO.log(stringify(help)!);
}

public printCurrentQuickInfo() {
Expand Down Expand Up @@ -3565,7 +3565,7 @@ ${code}
};
}

function stringify(data: any, replacer?: (key: string, value: any) => any): string {
function stringify<T>(data: T, replacer?: (key: string, value: any) => any) {
return JSON.stringify(data, replacer, 2);
}

Expand Down
6 changes: 4 additions & 2 deletions src/lib/es5.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1029,6 +1029,8 @@ interface URIErrorConstructor {

declare const URIError: URIErrorConstructor;

type StringifyReturnType<T> = T extends undefined ? string | undefined : string;

interface JSON {
/**
* Converts a JavaScript Object Notation (JSON) string into an object.
Expand All @@ -1043,14 +1045,14 @@ interface JSON {
* @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?: (this: any, key: string, value: any) => any, space?: string | number): string;
stringify<T>(value: T, replacer?: (this: any, key: string, value: any) => any, space?: string | number): StringifyReturnType<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 a 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(value: any, replacer?: (number | string)[] | null, space?: string | number): string;
stringify<T>(value: T, replacer?: (number | string)[] | null, space?: string | number): StringifyReturnType<T>;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/services/shims.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ namespace ts {
useCaseSensitiveFileNames?(): boolean;

getTypeRootsVersion?(): number;
readDirectory(rootDir: string, extension: string, basePaths?: string, excludeEx?: string, includeFileEx?: string, includeDirEx?: string, depth?: number): string;
readDirectory(rootDir: string, extension?: string, basePaths?: string, excludeEx?: string, includeFileEx?: string, includeDirEx?: string, depth?: number): string;
readFile(path: string, encoding?: string): string | undefined;
fileExists(path: string): boolean;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ namespace ts {
}

function assertCompilerOptionsWithJsonNode(json: any, configFileName: string, expectedResult: ExpectedResultWithParsingSuccess) {
assertCompilerOptionsWithJsonText(JSON.stringify(json), configFileName, expectedResult);
assertCompilerOptionsWithJsonText(JSON.stringify(json)!, configFileName, expectedResult);
}

function assertCompilerOptionsWithJsonText(fileText: string, configFileName: string, expectedResult: ExpectedResult) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ namespace ts {
}

function assertTypeAcquisitionWithJsonNode(json: any, configFileName: string, expectedResult: ExpectedResult) {
const fileText = JSON.stringify(json);
const fileText = JSON.stringify(json)!;
const result = parseJsonText(configFileName, fileText);
assert(!result.parseDiagnostics.length);
assert(!!result.endOfFileToken);
Expand Down
2 changes: 1 addition & 1 deletion src/testRunner/unittests/config/matchFiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ namespace ts {

function validateMatches(expected: ParsedCommandLine, json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[]) {
{
const jsonText = JSON.stringify(json);
const jsonText = JSON.stringify(json)!;
const result = parseJsonText(caseInsensitiveTsconfigPath, jsonText);
const actual = parseJsonSourceFileConfigFileContent(result, host, basePath, existingOptions, configFileName, resolutionStack);
for (const error of expected.errors) {
Expand Down
4 changes: 2 additions & 2 deletions src/testRunner/unittests/tsbuildWatchMode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -982,7 +982,7 @@ export function gfoo() {
const cTsConfigJson = JSON.parse(cTsconfig.content);
host.ensureFileOrFolder(nrefs);
cTsConfigJson.compilerOptions.paths = { "@ref/*": nrefsPath };
host.writeFile(cTsconfig.path, JSON.stringify(cTsConfigJson));
host.writeFile(cTsconfig.path, JSON.stringify(cTsConfigJson)!);
},
emptyArray,
expectedProgramFiles.map(nrefReplacer),
Expand Down Expand Up @@ -1015,7 +1015,7 @@ export function gfoo() {
const bTsConfigJson = JSON.parse(bTsconfig.content);
host.ensureFileOrFolder(nrefs);
bTsConfigJson.compilerOptions.paths = { "@ref/*": nrefsPath };
host.writeFile(bTsconfig.path, JSON.stringify(bTsConfigJson));
host.writeFile(bTsconfig.path, JSON.stringify(bTsConfigJson)!);
},
emptyArray,
expectedProgramFiles,
Expand Down
2 changes: 1 addition & 1 deletion src/testRunner/unittests/tscWatch/emit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ namespace ts.tscWatch {
(configObj.compilerOptions || (configObj.compilerOptions = {})).listEmittedFiles = true;
const configFile = getFileOrFolderEmit({
path: configFilePath,
content: JSON.stringify(configObj)
content: JSON.stringify(configObj)!
});

const files = [moduleFile1, file1Consumer1, file1Consumer2, globalFile3, moduleFile2, configFile, libFile, ...additionalFiles];
Expand Down
2 changes: 1 addition & 1 deletion src/testRunner/unittests/tscWatch/watchApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ namespace ts.tscWatch {
};
const config: File = {
path: `${projectRoot}/tsconfig.json`,
content: JSON.stringify(configFileJson)
content: JSON.stringify(configFileJson)!
};
const settingsJson: File = {
path: `${projectRoot}/settings.json`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ namespace ts.projectSystem {
const additionalFiles = getAdditionalFileOrFolder ? getAdditionalFileOrFolder() : [];
const configFile = {
path: configFilePath,
content: JSON.stringify(configObj || { compilerOptions: {} })
content: JSON.stringify(configObj || { compilerOptions: {} })!
};

const files: File[] = [file1Consumer1, moduleFile1, file1Consumer2, moduleFile2, ...additionalFiles, globalFile3, libFile, configFile];
Expand Down Expand Up @@ -525,7 +525,7 @@ namespace ts.projectSystem {
};

function eventToString(event: server.ProjectsUpdatedInBackgroundEvent) {
return JSON.stringify(event && { eventName: event.eventName, data: event.data });
return JSON.stringify(event && { eventName: event.eventName, data: event.data })!;
}

function eventsToString(events: ReadonlyArray<server.ProjectsUpdatedInBackgroundEvent>) {
Expand Down
2 changes: 1 addition & 1 deletion src/testRunner/unittests/tsserver/metadataInResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ namespace ts.projectSystem {
function verifyCommandWithMetadata<T extends server.protocol.Request, U = undefined>(session: TestSession, host: TestServerHost, command: Partial<T>, expectedResponseBody: U) {
command.seq = session.getSeq();
command.type = "request";
session.onMessage(JSON.stringify(command));
session.onMessage(JSON.stringify(command)!);
verifyOutput(host, expectedResponseBody ?
{ seq: 0, type: "response", command: command.command!, request_seq: command.seq, success: true, body: expectedResponseBody, metadata } :
{ seq: 0, type: "response", command: command.command!, request_seq: command.seq, success: false, message: "No content available." }
Expand Down
24 changes: 24 additions & 0 deletions tests/baselines/reference/json.stringify.errors.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
tests/cases/compiler/json.stringify.ts(8,7): error TS2322: Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
tests/cases/compiler/json.stringify.ts(9,7): error TS2322: Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.


==== tests/cases/compiler/json.stringify.ts (2 errors) ====
var value = null;
JSON.stringify(value, undefined, 2);
JSON.stringify(value, null, 2);
JSON.stringify(value, ["a", 1], 2);
JSON.stringify(value, (k) => undefined, 2);
JSON.stringify(value, undefined, 2);

const isUndefined: string = JSON.stringify(undefined);
~~~~~~~~~~~
!!! error TS2322: Type 'string | undefined' is not assignable to type 'string'.
!!! error TS2322: Type 'undefined' is not assignable to type 'string'.
const maybeUndefined: string = JSON.stringify("apple" as string | undefined);
~~~~~~~~~~~~~~
!!! error TS2322: Type 'string | undefined' is not assignable to type 'string'.
!!! error TS2322: Type 'undefined' is not assignable to type 'string'.
const isNotUndefined: string = JSON.stringify("banana");

10 changes: 9 additions & 1 deletion tests/baselines/reference/json.stringify.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@ JSON.stringify(value, undefined, 2);
JSON.stringify(value, null, 2);
JSON.stringify(value, ["a", 1], 2);
JSON.stringify(value, (k) => undefined, 2);
JSON.stringify(value, undefined, 2);
JSON.stringify(value, undefined, 2);

const isUndefined: string = JSON.stringify(undefined);
const maybeUndefined: string = JSON.stringify("apple" as string | undefined);
const isNotUndefined: string = JSON.stringify("banana");


//// [json.stringify.js]
var value = null;
Expand All @@ -13,3 +18,6 @@ JSON.stringify(value, null, 2);
JSON.stringify(value, ["a", 1], 2);
JSON.stringify(value, function (k) { return undefined; }, 2);
JSON.stringify(value, undefined, 2);
var isUndefined = JSON.stringify(undefined);
var maybeUndefined = JSON.stringify("apple");
var isNotUndefined = JSON.stringify("banana");
19 changes: 19 additions & 0 deletions tests/baselines/reference/json.stringify.symbols
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,22 @@ JSON.stringify(value, undefined, 2);
>value : Symbol(value, Decl(json.stringify.ts, 0, 3))
>undefined : Symbol(undefined)

const isUndefined: string = JSON.stringify(undefined);
>isUndefined : Symbol(isUndefined, Decl(json.stringify.ts, 7, 5))
>JSON.stringify : Symbol(JSON.stringify, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>JSON : Symbol(JSON, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>stringify : Symbol(JSON.stringify, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>undefined : Symbol(undefined)

const maybeUndefined: string = JSON.stringify("apple" as string | undefined);
>maybeUndefined : Symbol(maybeUndefined, Decl(json.stringify.ts, 8, 5))
>JSON.stringify : Symbol(JSON.stringify, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>JSON : Symbol(JSON, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>stringify : Symbol(JSON.stringify, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))

const isNotUndefined: string = JSON.stringify("banana");
>isNotUndefined : Symbol(isNotUndefined, Decl(json.stringify.ts, 9, 5))
>JSON.stringify : Symbol(JSON.stringify, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>JSON : Symbol(JSON, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>stringify : Symbol(JSON.stringify, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))

Loading