Last active
September 9, 2021 14:19
-
-
Save karol-majewski/818dc1a4569ac33c055830694ba726b3 to your computer and use it in GitHub Desktop.
Safe string for SWR inspired by https://github.com/vercel/swr/discussions/1247#discussion-3435275 (https://tsplay.dev/NBPy4W)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Returns a `string` if all parts of the created template string are guaranteed to be defined. | |
* If at least one partial string is nullable, the return value will be null. | |
* | |
* @example | |
* | |
* ```ts | |
* safestring`/api/v1/users/${user?.id}`; // string | null | |
* safestring`/api/v1/users/${"15"}`; // string | |
* ``` | |
*/ | |
function safestring(strings: TemplateStringsArray, ...args: Array<string | number>): string; | |
function safestring(strings: TemplateStringsArray, ...args: Array<string | number | null | undefined>): string | null; | |
function safestring(strings: TemplateStringsArray, ...args: Array<string | number | null | undefined>): string | null { | |
let result = strings[0]; | |
for (let index = 0; index < args.length; index++) { | |
if (args[index] == null) return null; | |
result += args[index]! + strings[index + 1]!; | |
} | |
return result ?? null; | |
} | |
declare const user: { | |
id?: string; | |
}; | |
const foo: string = safestring`/api/users/${'foo'}/projects.json`; | |
const bar: string | null = safestring`/api/users/${user.id}/projects.json`; |
Author
karol-majewski
commented
Sep 9, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment