Skip to content

Instantly share code, notes, and snippets.

@Grubba27
Created April 23, 2022 01:21
Show Gist options
  • Save Grubba27/b7516e944473f1a1c1a4204f37a03bc0 to your computer and use it in GitHub Desktop.
Save Grubba27/b7516e944473f1a1c1a4204f37a03bc0 to your computer and use it in GitHub Desktop.
Simple HTML parser
type λ<T, C> = {tag: T, content: C}
type HTMLParser
<
Text extends string,
Tag extends string = '',
Content extends string = ''
> =
Text extends `${infer L}${infer R}`
? L extends '<'
? HTMLParser<R, Tag, Content>
: L extends '>'
? λ<Tag, ContentParser<R>>
: L extends '/'
? λ<Tag, ContentParser<R>>
: HTMLParser<R, `${Tag}${L}`, Content>
: λ<Tag, Content>
type ContentParser
<Text extends string, Result extends string = ''> =
Text extends `${infer L}${infer R}`
? L extends '<'
? Result
: ContentParser<R, `${Result}${L}` >
: never
const h1: HTMLParser<'<h1>bla</h1>'>
const b: HTMLParser<'<br/>'>
const span: HTMLParser<'<span>fooo</span>'> = {tag: 'span', content: 'fooo'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment