[Vuejs]-Vue3 + TS: How to fix type 'never' for ref of empty array?

4πŸ‘

βœ…

The ref function is generic – it can infer the type of the value you want to store in the returned reference. Since you pass an empty array, the type that is inferred is never[], which means an array that will never have any elements. This is obviously not what you want. You could initialize the ref with an array that has a Todo, but that’s not ideal.

In this case, you need to tell TypeScript that you intend to store Todos in this array. You can do this by passing a type parameter to the ref function. Define a type or an interface for Todo and pass it like this:

type Todo = {
  id: number;
  title: string;
  completed: boolean;
}

const todos = ref<Todo[]>([]);

You can also do this inline:

const todos = ref<{ id: number; title: string; completed: boolean }[]>([]);
πŸ‘€Ali Nauman

1πŸ‘

I would create an interface for that. Also the usage of the generic ref<> make things easier.

ITodo.ts

export interface ITodo {
        id: number;
        title: string;
        completed: boolean;
    }

Component.vue

<script lang="ts">
import { computed, ref } from "vue";
import { defineComponent } from 'vue'
export default defineComponent ({
    setup() {
        const todo = ref<ITodo|undefined>(undefined);
        const todos = ref<ITodo[]>([]);
        let id = 0;
        const numberOfCompletedTodos = computed(
            () => todos.value.filter((todo) => todo.completed).length
        );
        function addTodo() {
            todos.value.push(todo.value);
            todo.value = undefined;
            id++;
        }
        function removeTodo(index) {
            todos.value.splice(index, 1);
        }
</script>
πŸ‘€MrSpt

Leave a comment