如何扩展Electron包的App类型?
扩展Electron App模块的类型定义问题
我尝试扩展Electron的app模块:
import { app } from "electron" app.foo = "bar" // Property 'foo' does not exist on type 'App'.ts(2339)
用//@ts-ignore能让代码正常运行,但我希望通过配置.d.ts文件覆盖类型,自己编写的文件却无效(刚接触类型覆盖)。
我的electron.d.ts文件内容:
import { App as ElectronApp } from "electron" declare module Electron { export interface App extends ElectronApp { inspect: boolean } }
正确的类型扩展方案
你写的.d.ts存在两处问题,调整后即可生效:
- 无需导入原有
App接口,TypeScript支持接口声明合并,直接在electron模块声明里扩展接口即可 - 确保
.d.ts文件被TypeScript识别(比如放在项目根目录,或者在tsconfig.json的include数组中配置该文件路径)
修改后的electron.d.ts内容:
declare module 'electron' { interface App { foo: string; // 对应你要添加的foo属性,可根据实际需求修改类型 inspect: boolean; } }
额外注意事项
- 检查
tsconfig.json的compilerOptions.typeRoots配置,确保包含当前.d.ts文件所在目录(默认会自动识别项目内的.d.ts和node_modules/@types,若自定义路径需手动调整) - 不需要继承原有
App接口,扩展的接口会自动与Electron原生的App接口合并,保留所有原有属性的同时添加新属性
调整完成后,TypeScript就能识别app对象的新属性,无需再使用//@ts-ignore规避类型检查。
内容的提问来源于stack exchange,提问作者sunknudsen
相关产品推荐
相关产品推荐

