我在 vue.js 3 typescript 中有這段程式碼,我只想在資料中宣告一個物件數組,但彈出幾個錯誤
<template> <ul > <li v-if="!items.length">...loading</li> <li v-for="item in items" :key="item.id"> <!--{{item}}--> <!--donde va {{item}} pongo un slot tag con un name y binding el item que voy a utilizar en el parent--> <slot name="item" v-bind="item"></slot> </li> </ul> </template> <script lang="ts"> import { defineComponent } from 'vue' export default defineComponent({ name: 'child-slot-component', data() { return { items: [] } }, mounted() { setTimeout(() => { this.items = [ { id: 1, body: 'Scoped Slots Guide', username: 'Evan You', likes: 20 }, { id: 2, body: 'Vue Tutorial', username: 'Natalia Tepluhina', likes: 10 } ] }, 1000) }, }) </script> <style scoped> ul{ list-style-type: none; } </style>
id、正文、使用者名稱和按讚類型「number」或「string」不可指派給「never」類型。 ts(2322) 因為在資料中,當宣告具有空數組的專案時,它說 property:never 並且我想宣告如下內容: {id:number, body:string,username:string, likes:number}[]
如果不正確,使用打字稿處理此聲明的正確方法是什麼,或者我可能需要配置 tsconfig.json 或其他內容
提前致謝 哦,該應用程式運行良好! !
這是我的 tsconfig.json:
{ "compilerOptions": { "target": "esnext", "module": "esnext", "strict": true, "jsx": "preserve", "moduleResolution": "node", "experimentalDecorators": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "forceConsistentCasingInFileNames": true, "useDefineForClassFields": true, "sourceMap": true, "baseUrl": ".", "types": [ "webpack-env" ], "paths": { "@/*": [ "src/*" ] }, "lib": [ "esnext", "dom", "dom.iterable", "scripthost" ] }, "include": [ "src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", "tests/**/*.ts", "tests/**/*.tsx" ], "exclude": [ "node_modules" ] }
這是我的 vue.config.js
const { defineConfig } = require('@vue/cli-service') module.exports = defineConfig({ transpileDependencies: true })我的巴貝爾設定
module.exports = { presets: [ '@vue/cli-plugin-babel/preset' ] }我的 shims-vue.d.ts
/* eslint-disable */ declare module '*.vue' { import type { DefineComponent } from 'vue' const component: DefineComponent<{}, {}, any> export default component }和我的 .eslintrc.js#
module.exports = { root: true, env: { node: true }, 'extends': [ 'plugin:vue/vue3-essential', 'eslint:recommended', '@vue/typescript/recommended' ], parserOptions: { ecmaVersion: 2020 }, rules: { 'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off', 'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off' } }###只是帶有vue create app-name的預設配置###
P粉7757237222023-11-03 09:05:25
提前使用類型定義項目陣列應該可以修復 TypeScript 錯誤。像這樣的東西應該有效:
items: [] as { id: number, body: string, username: string, likes: number }[]