如何在TypeScript中使用Cordova插件?Android开发报错求助
Hey there, let's sort out that frustrating TS2304 error you're hitting when using cordova-plugin-sms with TypeScript. The core issue here is that TypeScript doesn't recognize the global SMS object injected by the Cordova plugin at runtime—unlike plain JavaScript, which happily accepts global variables without question.
Here are a few straightforward fixes to get your code working again:
1. Quick Fix: Declare the Global Variable Directly in Your File
If you want a fast, no-fuss solution, just add a declaration at the top of your manageSMS.ts file to tell TypeScript the SMS variable exists:
// Let TypeScript know SMS is a global variable declare var SMS: any; // Now your existing SMS-related code will compile without errors SMS.send({ phone: '1234567890', text: 'Test message from TypeScript!' }, () => console.log('SMS sent successfully'), (err) => console.error('SMS error:', err));
2. Cleaner Fix: Create a Project-Wide Type Declaration File
For a more scalable approach (and to get basic IDE hints), create a custom TypeScript declaration file (e.g., src/types/cordova-plugins.d.ts) and define the SMS plugin's type structure:
// src/types/cordova-plugins.d.ts interface SMSPlugin { send(options: { phone: string; text: string; // Add other supported options here if needed }, successCallback: () => void, errorCallback: (error: string) => void): void; // Include other plugin methods you use, like listMessages listMessages(filter: any, successCallback: (messages: any[]) => void, errorCallback: (error: string) => void): void; } declare var SMS: SMSPlugin;
Then update your tsconfig.json to include this directory so TypeScript picks up the declaration:
{ "include": [ "src/**/*", "src/types/**/*" ] }
3. Critical Check: Wait for the Cordova Deviceready Event
Even with proper type declarations, you need to ensure the Cordova plugin is fully loaded before calling any SMS methods. Always wrap your plugin logic inside the deviceready listener:
document.addEventListener('deviceready', () => { // Safe to use SMS here—Cordova has finished loading all plugins SMS.send(/* your message options */); }, false);
Why This Happened
In plain JavaScript, Cordova injects the SMS object into the global window object at runtime, and JS doesn't care that it wasn't defined upfront. TypeScript, being a statically typed language, checks for variable existence during compilation—since it can't see the runtime-injected SMS, it throws that "Cannot find name" error.
内容的提问来源于stack exchange,提问作者neiya

