如何从WebPage接口的property函数参数提取字符串字面量类型?
解决TypeScript提取WebPage.property参数类型为字面量联合的问题
问题原因
你遇到的情况是因为TypeScript可能将字面量联合类型自动拓宽为string,或者@types/phantom包的实际类型定义中,property方法的key参数被定义为宽泛的string类型,而非你预期的字符串字面量联合。
解决方案
方案1:确保TypeScript严格模式开启
检查你的tsconfig.json,确保开启strict模式,这会阻止字面量类型被自动拓宽:
{ "compilerOptions": { "strict": true, // 其他配置... } }
开启后,你的原有代码应该能正确将T推断为目标字面量联合类型:
async getPageProperty<T extends Parameters<WebPage["property"]>[0]>(url: string, property: T){ // ... }
方案2:显式提取并定义类型别名
如果严格模式开启后仍未解决,可以显式提取目标类型并复用:
// 从WebPage接口提取property的key类型 type WebPagePropertyKey = Parameters<WebPage["property"]>[0]; async getPageProperty<T extends WebPagePropertyKey>(url: string, property: T) { // ... }
方案3:扩充@types/phantom的类型定义
如果@types/phantom包的实际类型定义中key参数是string(而非字面量联合),可以通过模块扩充修改类型:
declare module 'phantom' { interface WebPage { property( key: | "content" | "plainText" | "focusedFrameName" | "frameContent" | "frameName" | "framePlainText" | "frameTitle" | "libraryPath" | "offlineStoragePath" | "title" | "url" | "windowName", ): Promise<string>; } }
扩充后,再使用Parameters提取就能得到正确的字面量联合类型。
内容的提问来源于stack exchange,提问作者stealing_society
相关产品推荐
相关产品推荐

