Mar*_*ear 2 typescript nativescript
打字稿书呆子我有这个代码:
import * as appSettings from 'application-settings';
try {
// shim the 'localStorage' API with application settings module
global.localStorage = {
getItem(key: string) {
return appSettings.getString(key);
},
setItem(key: string, value: string) {
return appSettings.setString(key, value);
}
}
application.start({ moduleName: 'main-page' });
}
catch (err) {
console.log(err);
}
Run Code Online (Sandbox Code Playgroud)
...VScode 给了我[ts] Property 'localStorage' does not exist on type 'Global'. [2339]关于如何解决这个错误的想法?
这是一个 Nativescript 应用程序。参考这里是整个文件/应用程序:https : //github.com/burkeholland/nativescript-todo/blob/master/app/app.ts
这是 TypeScript 的预期,类型global不包括,localStorage所以它只是试图让你知道它是一个无效的属性。
您可以通过将其强制转换为 any 来简单地克服该错误。
(<any>global).localStorage = {
getItem(key: string) {
return appSettings.getString(key);
},
setItem(key: string, value: string) {
return appSettings.setString(key, value);
}
}
Run Code Online (Sandbox Code Playgroud)
你甚至可能会延长global从分型references.d.ts,它通常位于项目的根。如果不存在,您可以创建一个。
declare namespace NodeJS {
interface Global {
localStorage: { getItem: (key: string) => any; setItem: (key: string, value: string) => any; };
}
}
Run Code Online (Sandbox Code Playgroud)