Question:
Javascript Error Solved: Property 'id' does not exist on type 'T'

Problem

Learning typescript. Here is the code:


interface TodoI {

    id: number;

    title: string;

    status: string;

    completedOn?: Date;

}


const todoItems: TodoI[] = [

    { id: 1, title: "Learn HTML", status: "done", completedOn: new Date("2021-09-11") },

    { id: 2, title: "Learn TypeScript", status: "in-progress" },

    { id: 3, title: "Write the best app in the world", status: "todo", },

]


function addTodoItem(todo: string): TodoI {

    const id = getNextId<TodoI>(todoItems)


    const newTodo = {

        id,

        title: todo,

        status: "todo",

    }


    todoItems.push(newTodo)


    return newTodo

}


function getNextId<T>(items: T[]) : number {

    // following line is causing the issue

    // Property 'id' does not exist on type 'T'.ts(2339)

    return items.reduce((max, x) => x.id > max ? x.id : max, 0) + 1

}


const newTodo = addTodoItem("Buy lots of stuff with all the money we make from the app")


console.log(JSON.stringify(newTodo))


While calling the getNextId() function I've specified type type TodoI, then why I am supposed to extend the generic type?


Solution

Where you've defined getNextId, the generic type T argument has no properties, equivalent to any. Your function cannot know that T has an id property.


The simplest solution is to enforce the generic type T extends a type with an id property


function getNextId<T extends { id: number }>(items: T[]): number {

  return items.reduce((max, x) => (x.id > max ? x.id : max), 0) + 1;

}



FYI because the type passed to your function is inferred by the argument, you don't need to use generics when calling it


const id = getNextId(todoItems);



Suggested blog

>How to get the date and time and display it in a defineProps in Vuejs?

>Why logged user object is all strings in Vuejs and Laravel 10?

>What is meant by progressive framework?

>How can I replace this.$parent in composition API in Vuejs?

>How do I fix an invalid route component in the new VueJs Project?

>How to get all the rows selected in Vuejs?

>How to set up a dynamic grid based on flex or grid in Vuejs?


Nisha Patel

Nisha Patel

Submit
0 Answers