在Svelte中为非标准window:beforeinstallprompt事件添加TS类型声明
Got it, let's fix this TypeScript error when using the beforeinstallprompt event with <svelte:window> in Svelte. The issue is that TypeScript doesn't recognize this non-standard PWA event in Svelte's built-in window props by default, but we can extend the type definitions to make it work without switching to onMount:
Step 1: Create a Type Declaration File
In your Svelte + TypeScript project, create a new file (e.g., src/svelte-window-extensions.d.ts) in your source directory. This file will hold our custom type extensions.
Step 2: Add the Extended Type Definitions
Paste the following code into the file:
// src/svelte-window-extensions.d.ts import type { SvelteWindowProps } from 'svelte'; // Define the full type for the non-standard BeforeInstallPromptEvent interface BeforeInstallPromptEvent extends Event { readonly platforms: string[]; readonly userChoice: Promise<{ outcome: 'accepted' | 'dismissed'; platform: string; }>; prompt(): Promise<void>; } // Extend Svelte's window props to include the event handler declare module 'svelte' { interface SvelteWindowProps { onbeforeinstallprompt?: (event: BeforeInstallPromptEvent) => void; } }
This does two critical things:
- It defines the complete type for
BeforeInstallPromptEvent, so you get proper type checking for its methods likeprompt()and properties likeuserChoice. - It merges the new event handler into Svelte's
SvelteWindowPropsinterface—the type that governs<svelte:window>props—so TypeScript recognizes it as a valid prop.
Step 3: Ensure TypeScript Picks Up the File
Double-check your tsconfig.json to make sure it includes your .d.ts file. Your include array should look similar to this:
{ "include": ["src/**/*.d.ts", "src/**/*.svelte", "src/**/*.ts"] }
Step 4: Use the Event in App.svelte
Now you can use the event with <svelte:window> without TypeScript errors, and with full type safety:
<script lang="ts"> let deferredPrompt: BeforeInstallPromptEvent | null = null; function handleBeforeInstallPrompt(e: BeforeInstallPromptEvent) { e.preventDefault(); // Save the event to trigger later (e.g., when the user clicks an install button) deferredPrompt = e; console.log('PWA install prompt is ready'); } // Example: Trigger the install prompt on user action function triggerInstall() { if (deferredPrompt) { deferredPrompt.prompt(); deferredPrompt.userChoice.then((result) => { console.log(`User ${result.outcome === 'accepted' ? 'accepted' : 'dismissed'} the prompt`); deferredPrompt = null; }); } } </script> <svelte:window on:beforeinstallprompt={handleBeforeInstallPrompt} /> {#if deferredPrompt} <button on:click={triggerInstall}>Install Our App</button> {/if}
That's all! The TypeScript error should vanish, and you'll get proper intellisense for the PWA install event.
内容的提问来源于stack exchange,提问作者Christian

