I have this code in vue.js 3 typescript, I just want to declare an array of objects in the data, but several errors pop up
<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, body, username and like type "number" or "string" are not assignable to type "never". ts(2322) Because in the data when declaring an item with an empty array it says property:never and I want to declare something like this: {id:number, body:string,username:string, likes:number}[]
If not correct, what is the correct way to handle this declaration using typescript or maybe I need to configure tsconfig.json or something
Thanks in advance Oh, the app works great! !
This is my 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" ] }
This is my vue.config.js
const { defineConfig } = require('@vue/cli-service') module.exports = defineConfig({ transpileDependencies: true })
My Babel Configuration
module.exports = { presets: [ '@vue/cli-plugin-babel/preset' ] }
My shims-vue.d.ts
/* eslint-disable */ declare module '*.vue' { import type { DefineComponent } from 'vue' const component: DefineComponent<{}, {}, any> export default component }
and my .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' } }
Just the default configuration with vue create app-name
Defining an array of items with types ahead of time should fix TypeScript errors. Something like this should work: