From fc8da34baabd07b68bc6ba79a9d3d149ec3d6ecb Mon Sep 17 00:00:00 2001 From: Samuel Attard Date: Sun, 22 Sep 2024 19:51:54 -0700 Subject: [PATCH] fix: better handling of union return types (#121) --- src/__tests__/markdown-helpers.spec.ts | 11 +++++++++++ src/markdown-helpers.ts | 8 ++++++++ 2 files changed, 19 insertions(+) diff --git a/src/__tests__/markdown-helpers.spec.ts b/src/__tests__/markdown-helpers.spec.ts index 899d769..3a5a590 100644 --- a/src/__tests__/markdown-helpers.spec.ts +++ b/src/__tests__/markdown-helpers.spec.ts @@ -474,6 +474,17 @@ foo`), }); }); + it('should helpfully error for badly formatted union return types', () => { + const customTokens = getTokens( + `Returns \`WebContents\` | \`string\` - A WebContents instance with the given ID.`, + ); + expect(() => extractReturnType(customTokens)).toThrowErrorMatchingInlineSnapshot(` + "Found a return type declaration that appears to be declaring a type union (A | B) but in the incorrect format. Type unions must be fully enclosed in backticks. For instance, instead of \`A\` | \`B\` you should specify \`A | B\`. + Specifically this error was encountered here: + "Returns \`WebContents\` | \`string\` - A WebContents instance with the given ID."..." + `); + }); + it('should handle return types with no descriptions', () => { const printerTokens = getTokens(`Returns [\`PrinterInfo[]\`](structures/printer-info.md)`); const printerRet = extractReturnType(printerTokens); diff --git a/src/markdown-helpers.ts b/src/markdown-helpers.ts index c9cf18a..6413a10 100644 --- a/src/markdown-helpers.ts +++ b/src/markdown-helpers.ts @@ -530,6 +530,14 @@ export const extractReturnType = ( } catch {} } + if (parsedDescription.trim().startsWith('|')) { + throw new Error( + `Found a return type declaration that appears to be declaring a type union (A | B) but in the incorrect format. Type unions must be fully enclosed in backticks. For instance, instead of \`A\` | \`B\` you should specify \`A | B\`.\nSpecifically this error was encountered here:\n "${rawDescription + .trim() + .slice(0, 100)}"...`, + ); + } + return { parsedDescription: parsedDescription.trim(), parsedReturnType: rawTypeToTypeInformation(rawReturnType, parsedDescription, typedKeys),