ts提示 找不到名称“localStorage”。ts(2304) ?

vue3 + ts项目,使用localStorage获取本地存储,ts报错

image.png
这该咋整?

阅读 5.5k
2 个回答

tsconfig.json

{
  "compilerOptions": {
    "lib": ["ESNext", "DOM", "DOM.Iterable"],
}

localStorage 是 DOM 的内容,需要声明包含 DOM 库

declare global {
  interface Window {
    localStorage: Storage;
  }
}

tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "isolatedModules": false,
    "noImplicitAny": false, // 默认不声明类型的时候为any
    "types": [
      "vite/client",
      "node"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}
推荐问题
logo
Microsoft
子站问答
访问
宣传栏