Skip to content

Instantly share code, notes, and snippets.

@MasterTuto
Created June 11, 2025 21:38
Show Gist options
  • Select an option

  • Save MasterTuto/2ca2315104994c6a1619d976b680c719 to your computer and use it in GitHub Desktop.

Select an option

Save MasterTuto/2ca2315104994c6a1619d976b680c719 to your computer and use it in GitHub Desktop.
type WhiteSpace<T extends string> = T extends ` ${infer S}` ? WhiteSpace<S> : T;
namespace If {
export type Output<Cond=any, Cont=any, ElseIf=any, Else=any> = {
type: 'if',
condition: Cond,
content: Cont
}
export type Match<Source extends string> = Source extends `if${'(' | ' '}${string}` ? true : false;
export type Block<Source extends string> =
WhiteSpace<Source> extends `if${string}(${infer Condition extends string})${infer IfBodyOut extends string}`
? WhiteSpace<IfBodyOut> extends `{${infer IfBodyIn extends string}}${infer IfContinuation extends string}`
? WhiteSpace<IfContinuation> extends `else${infer RestElse extends string}`
? WhiteSpace<RestElse> extends `{${infer ElseBody extends string}`
? Output<Parser<Condition>, Parser<IfBodyIn>, undefined, Parser<ElseBody>>
: WhiteSpace<RestElse> extends `if${infer RestElseIf extends string}`
? Output<Parser<Condition>, Parser<IfBodyIn>, Block<RestElseIf>, undefined>
: never
: Output<Parser<Condition>, Parser<IfBodyIn>, undefined, undefined>
: never
: never;
}
type Parser<Source extends string> =
If.Block<Source> extends infer Output extends If.Output
? Output
: 'Error: wrong syntax'
type Test = Parser<"if (true) {false}">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment