这是一个大项目的一部分,我基本上是为我正在制作的一种编辑器创建虚拟HTML元素.我花了很长时间试图缩小范围,我得到了下面的片段.更改这个代码段中的许多随机内容可以消除错误.即使删除hChildren
中的一个也会删除错误.这是Playground link.我们将不胜感激.
const elements = ["h1", "h2", "h3", "h4", "button"] as const;
const hChildren = [
"Welcome to Our Website!",
"Hello, World!",
"Discover More",
"Explore Our Services",
"Get Started Today",
"About Us",
"Contact Us",
] as const;
const buttonChildren = ["Browse"] as const;
function getRandomValue<T extends readonly string[]>(arr: T): T[number] {
const randomIndex = Math.floor(Math.random() * arr.length);
return arr[randomIndex];
}
const thisWorksAsExpected = (tagName: TagName) => {
if (tagName === "h1" || tagName === "h2" || tagName === "h3") {
return {
tagName,
children: getRandomValue(hChildren),
};
}
return {
tagName,
};
};
const thisDoesntWorkAsExpected = (tagName: TagName) => {
if (
tagName === "h1" ||
tagName === "h2" ||
tagName === "h3" ||
tagName === "h4"
) {
return {
tagName,
children: getRandomValue(hChildren),
};
}
return {
tagName,
};
};
type TagName = (typeof elements)[number];
type BaseElement<T extends TagName, C extends string> = {
tagName: T;
children?: C;
};
type VirtualElement =
| BaseElement<"h1", (typeof hChildren)[number]>
| BaseElement<"h2", (typeof hChildren)[number]>
| BaseElement<"h3", (typeof hChildren)[number]>
| BaseElement<"h4", (typeof hChildren)[number]>
| BaseElement<"button", (typeof buttonChildren)[number]>;
elements.forEach((tagName) => {
const builtVirtualElement1: VirtualElement = thisWorksAsExpected(tagName);
console.log(builtVirtualElement1);
const builtVirtualElement2: VirtualElement = thisDoesntWorkAsExpected(tagName);
console.log(builtVirtualElement2);
});