From ec25d0776b5f2b72d7693fb81c5044c9802c4b3d Mon Sep 17 00:00:00 2001 From: Samuel Attard Date: Sun, 22 Sep 2024 17:53:01 -0700 Subject: [PATCH] fix: better handling of union return types Fixes #93 It's non trivial to support this syntax so let's spit out a helpful error message instead. --- src/__tests__/markdown-helpers.spec.ts | 11 +++++++++++ src/markdown-helpers.ts | 6 ++++++ 2 files changed, 17 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..04f3935 100644 --- a/src/markdown-helpers.ts +++ b/src/markdown-helpers.ts @@ -530,6 +530,12 @@ 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),