Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeScript types #56

Open
drachehavoc opened this issue Sep 29, 2021 · 1 comment
Open

TypeScript types #56

drachehavoc opened this issue Sep 29, 2021 · 1 comment

Comments

@drachehavoc
Copy link

I greatly appreciate this library, but I miss types for TypeScript, so I wrote a d.ts for my use, but I'd like to share it with you developers

Below is the d.ts I created:

html-parse-stringify.d.ts

type AstElement = {
    tag: 'tag' | 'text' | 'component'
    name: string
    attrs?: { [attributeName: string]: string }
    voidElement?: boolean
    children?: AstElement[]
}

declare type Htmlparsestringify = {
    parse(htmlString: string, options?: any): AstElement[]
    stringify(AST: AstElement[]): string
}

declare module "html-parse-stringify" {
    export default null as Htmlparsestringify
}
@bfricka
Copy link

bfricka commented May 11, 2022

Should be:

type TagNode = {
  attrs: { [attr: string]: string }
  children: HTMLAstNode[]
  name: string
  type: 'tag'
  voidElement: boolean
}

type TextNode = {
  content: string
  type: 'text'
}

type ComponentNode = {
  attrs: { [attr: string]: string }
  children: []
  name: string
  type: 'component'
  voidElement: boolean
}

type HTMLAstNode = ComponentNode | TagNode | TextNode

So we can do type discrimination:

const foo = (node: HTMLAstNode) => {
  if (node.type === 'tag') {
    // node is TagNode
  }
}

Additionally, types should be exported from module so we can import type { HTMLAstNode } from 'html-parse-stringify'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants