-
This code: import { fromHtml } from "hast-util-from-html";
import { select } from "hast-util-select";
const tree = fromHtml("<h1>Hi</h1>>", { fragment: true });
console.log(select("h1", tree)!.children[0].value); creates this error
How can I fix that? Also, why is the text considered as a child of the tag? Shouldn't the children property only contain other elements? The |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
TypeScript gives you a type error because you have a type error. How to use TS: You store things in variables, and perform checks on them: const tree = fromHtml("<h1>Hi</h1>>", { fragment: true }); // Root
const h1 = select("h1", tree) // Element
if (!h1) throw new Error("main heading missing")
const head = h1.children[0] // ElementContent
if (head.type !== 'text') throw new Error("there are non-text things in the head!")
console.log(head.value) However, do not do you want you do. Your goal is to get the text of a heading. Headings can contain other things than text (as the types indicate). If you want text, use a tool for that: import {toText} from 'hast-util-to-text'
const tree = fromHtml("<h1>Hi</h1>>", { fragment: true }); // Root
const h1 = select("h1", tree) // Element
if (!h1) throw new Error("main heading missing")
const text = toText(h1) // string See also:
No, that is not needed. There is no such restriction.
Anything could be done. But some things are not good things. This is not a good thing. There would be different sources of truth. Which will bite everyone in their butt. |
Beta Was this translation helpful? Give feedback.
TypeScript gives you a type error because you have a type error.
If you want types, use TS. TS will give you errors when you make problems. This is that.
How to use TS:
You store things in variables, and perform checks on them:
However, do not do you want you do. Your goal is to get the text of a heading. Headings can contain other things than text (as the types indicate). If you wan…