You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Window添加Electron API类型以实现Svelte中的类型校验?

解决Svelte中Electron IPC API的TypeScript类型报错问题

核心问题原因

你定义的Window接口未被TypeScript正确识别,全局接口扩展必须包裹在declare global块中,同时文件需要通过导出空对象标记为模块。

步骤1:修正global.d.ts的定义

将global.d.ts修改为以下格式,确保全局接口被正确扩展:

// global.d.ts
declare global {
  interface Window {
    api: {
      GetVersion: () => Promise<string>;
      // 后续新增的IPC方法可在此补充类型定义
    };
  }
}

// 必须导出空对象,让TypeScript将此文件视为模块
export {};

步骤2:验证tsconfig.json配置

确保tsconfig.json的include字段包含global.d.ts文件,示例配置:

{
  "compilerOptions": {
    // 你的现有配置项
  },
  "include": ["src/**/*", "global.d.ts"]
}

步骤3:(可选)抽离公共类型提升维护性

若后续需新增更多IPC方法,可将API类型抽为单独文件,避免重复定义:

// src/types/electron-api.ts
export interface ElectronAPI {
  GetVersion: () => Promise<string>;
  // 新增方法示例
  GetAppPath: () => Promise<string>;
}

在preload.ts和global.d.ts中复用该类型:

// preload.ts
import type { ElectronAPI } from './types/electron-api';
import { contextBridge, ipcRenderer } from 'electron';

const WINDOW_API: ElectronAPI = {
  GetVersion: () => ipcRenderer.invoke("get/version"),
  GetAppPath: () => ipcRenderer.invoke("get/app-path")
};

contextBridge.exposeInMainWorld("api", WINDOW_API);
// global.d.ts
import type { ElectronAPI } from './src/types/electron-api';

declare global {
  interface Window {
    api: ElectronAPI;
  }
}

export {};

验证效果

现在在Svelte文件中使用window.api时,TypeScript会自动提供类型提示,且不再报Property 'api' does not exist错误:

<script lang="ts">
  let version: string | null = null;

  const getVersion = async () => {
    version = await window.api.GetVersion();
  };
</script>

<button on:click={getVersion}>获取应用版本</button>
{#if version}
  <p>当前版本:{version}</p>
{/if}

内容的提问来源于stack exchange,提问作者Lae

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 20:27:21