refactor: 优化extractText函数的类型声明,增强类型安全性

This commit is contained in:
2025-07-28 11:24:57 +08:00
parent ceb8357dc8
commit 460ed87ad2

View File

@ -2,26 +2,31 @@
import React from "react"; import React from "react";
import { toast } from "sonner"; import { toast } from "sonner";
function extractText(node: any): string { // 更安全的类型声明
function extractText(node: React.ReactNode): string {
if (typeof node === "string") return node; if (typeof node === "string") return node;
if (Array.isArray(node)) return node.map(extractText).join(""); if (Array.isArray(node)) return node.map(extractText).join("");
if (node && typeof node === "object" && "props" in node) { if (
return extractText(node.props.children); React.isValidElement(node) &&
node.props &&
typeof node.props === "object" &&
"children" in node.props
) {
return extractText(node.props.children as React.ReactNode);
} }
return ""; return "";
} }
export default function CodeBlock(props: React.ComponentPropsWithoutRef<"pre">) { export default function CodeBlock(props: React.ComponentPropsWithoutRef<"pre">) {
let className: string | undefined = undefined; let className: string | undefined = undefined;
const child = props.children as React.ReactElement<{ className?: string; children?: React.ReactNode }> | undefined;
if ( if (
props.children && child &&
typeof props.children === "object" && typeof child === "object" &&
"props" in props.children && "props" in child &&
props.children && child.props.className
typeof (props.children as any).props === "object" &&
(props.children as any).props.className
) { ) {
className = (props.children as any).props.className as string | undefined; className = child.props.className as string | undefined;
} }
let language = ""; let language = "";
if (className) { if (className) {
@ -32,12 +37,11 @@ export default function CodeBlock(props: React.ComponentPropsWithoutRef<"pre">)
} }
let codeContent = ""; let codeContent = "";
if ( if (
props.children && child &&
typeof props.children === "object" && typeof child === "object" &&
"props" in props.children && "props" in child
(props.children as any).props
) { ) {
codeContent = extractText((props.children as any).props.children); codeContent = extractText(child.props.children);
} }
function handleCopy(e: React.MouseEvent<HTMLButtonElement>) { function handleCopy(e: React.MouseEvent<HTMLButtonElement>) {