Skip to content

Instantly share code, notes, and snippets.

@gongpeione
Last active May 4, 2022 09:27
Show Gist options
  • Save gongpeione/7407a37e19fd3b827dcdefc34a9542d6 to your computer and use it in GitHub Desktop.
Save gongpeione/7407a37e19fd3b827dcdefc34a9542d6 to your computer and use it in GitHub Desktop.
Get string template variables
// if you have a object like this
// {
// tpl1: `Hello {name}, welcome to {location}`,
// tpl2: `yo {bro}`,
// }
// and you wanna get a type like this
// {
// name: string,
// location: string,
// bro: string
// }
type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
type PickAndFlatten<T, K extends keyof T> = UnionToIntersection<T[K]>;
type GetTemplateVariables<T> = T extends '' ? {} :
T extends `${infer P}{${infer B}}${infer S}`
? { [T in B]: string } | GetTemplateVariables<S>
: unknown;
// T extends `{${infer B}}${infer S}` ? GetAllTemplateVariables<S> : unknown;
type GetAllTemplateVariables<T> = {
[P in keyof T]: GetTemplateVariables<T[P]>;
}
const t1 = {
a: ` {var1} dfadf {var12} `,
b: `{var2}`
} as const;
const t1Vars: PickAndFlatten<GetAllTemplateVariables<typeof t1>, keyof typeof t1> = {} as any;
// t1Vars: {
// var1: string;
// } & {
// var12: string;
// } & {
// var2: string;
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment