如何在TypeScript中从Record<string, Type>类型的PageProps提取指定RichText类型
从Record类型的PageProps中提取特定子类型的解决方案
我明白你遇到的问题了——面对一个不能修改的PageProps类型(它是个Record<string, ...>结构),想从中提取出特定的RichText子类型,但用Pick和Extract直接组合没效果对吧?别担心,这里有个可行的方案:
解决方案代码
首先保留原有的PageProps类型(因为不能修改),然后通过索引访问类型+Extract的组合来提取目标类型:
// 原有的不可修改的PageProps类型 type PageProps = Record< string, | { type: "title"; title: Array<{ type: "text"; text: { content: string; link: { url: string; } | null; }; plain_text: string; href: string | null; }>; } | { type: "rich_text"; rich_text: Array< | { type: "text"; text: { content: string; link: { url: string; } | null; }; plain_text: string; href: string | null; } | { type: "equation"; equation: { expression: string; }; plain_text: string; href: string | null; } >; id: string; } | { type: "number"; number: number; id: string; } | { type: "url"; url: string; id: string; } >; // 提取目标RichText类型 type RichText = Extract<PageProps[string], { type: "rich_text" }>;
验证效果
你可以在TS Playground里测试下面的代码,确认类型推断正确:
// 这个变量会被正确推断为RichText类型 const validRichText: RichText = { type: "rich_text", id: "content-block-001", rich_text: [ { type: "text", text: { content: "Hello World", link: { url: "https://example.com" } }, plain_text: "Hello World", href: "https://example.com" }, { type: "equation", equation: { expression: "a² + b² = c²" }, plain_text: "a² + b² = c²", href: null } ] }; // 如果传入不符合RichText的结构,TypeScript会报错 const invalidRichText: RichText = { type: "title", // ❌ 类型不匹配,会报错 title: [] };
为什么之前的方法没用?
Pick工具类型的作用是选择对象的键,而我们要处理的是Record的值类型,所以它不适用;- 直接用
Extract而不先取PageProps[string]的话,Extract会把整个Record<string, ...>类型作为处理对象,无法定位到内部的联合值类型。
通过PageProps[string]先获取到Record所有值的联合类型,再用Extract筛选出type为"rich_text"的成员,就能精准得到你想要的RichText类型了。
内容的提问来源于stack exchange,提问作者GorvGoyl
相关产品推荐
相关产品推荐

