Last active
September 17, 2022 06:41
-
-
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)
This file contains 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 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