Skip to content

Instantly share code, notes, and snippets.

@joaomilho
Last active Mar 20, 2021
Embed
What would you like to do?
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