I have this piece of code in vue.js 3 typescript, and I just want to declare an array of objects in my data, but several error pops 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 likes yell Type 'number' or 'string' is not assignable to type 'never'.ts(2322) because in data when declaring items with empty array it says property:never and I wanted to declare something like this: {id:number, body:string,username:string, likes:number}[]
if is not correct what is the proper way to handle this declaration using typescript, or maybe I need to configure tsconfig.json or something
thanks in advance Oh and the app works fine!!
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 config
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'
}
}
is just the default configuration that brings vue create app-name
CodePudding user response:
Defining your items array with a type ahead of time should fix your TypeScript error. Something like this should work:
items: [] as { id: number, body: string, username: string, likes: number }[]