Created
April 5, 2022 12:18
-
-
Save FrameMuse/b3aae24540838c2c66ebf0284aceaeda to your computer and use it in GitHub Desktop.
Just a plain interpolation utility but with extracted interpolations to have a look of what variables you can interpolate into
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
type ExtractInterpolations<T extends string> = T extends `${infer _Start}{${infer V}}${infer Rest}` ? V | ExtractInterpolations<Rest> : never | |
/** | |
* Interpolates {variable} in string | |
*/ | |
function interpolate<T extends string>(value: T, vars: Record<ExtractInterpolations<T>, string | number>): string { | |
const varKeys = Object.keys(vars) as ExtractInterpolations<T>[] | |
return varKeys.reduce((result: string, next) => result.replace(new RegExp(`{${next}}`, "g"), String(vars[next])), value) | |
} | |
export default function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment