Skip to content

Instantly share code, notes, and snippets.

@joaomilho
Last active September 17, 2022 06:41
Show Gist options
  • Save joaomilho/d31a4557f1b850ec7e65730a4316c80b to your computer and use it in GitHub Desktop.
Save joaomilho/d31a4557f1b850ec7e65730a4316c80b to your computer and use it in GitHub Desktop.
A printf with dependant types in TypeScript, similar to Idris (https://gist.github.com/chrisdone/672efcd784528b7d0b7e17ad9c115292)
type FieldType<Field> =
's' extends Field ? string :
'f' extends Field ? number :
'i' extends Field ? number :
'd' extends Field ? number :
'o' extends Field ? HTMLElement :
'O' extends Field ? object :
'c' extends Field ? string :
never;
type ExtractFields<T> =
T extends `${infer _}%${infer Field}${infer R}` ? [FieldType<Field>, ...ExtractFields<R>] :
T extends `${infer _}%${infer Field}` ? [FieldType<Field>] :
[];
function log<Fmt extends string>(
fmt: Fmt,
...args: ExtractFields<Fmt>
): void {
console.log(fmt, ...args);
};
log("Stuff: %s %f %O", 'Hello', 123, { ok: true });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment