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