EDIT: VLAZ's link's accepted answer was helpful - Types in object destructuring
None of the other questions I read before making this post applied to what I'm looking for, I think.
For this example I'm using axios to make a GET request to jsonplaceholder.
const url = 'https://jsonplaceholder.typicode.com/todos/1';
axios.get(url).then((res) => {})
The res object has a data
property, which I want to destructure and call it todo
Without typescript, I would have this:
axios.get(url).then((res) => {
const { data: todo } = res;
const ID = todo.id;
const title = todo.title;
const completed = todo.completed;
console.log(ID, title, completed)
});
It works, but I want to make an interface for the todo
variable:
interface Todo {
id: number;
title: string;
completed: boolean;
}
How do I cast the todo variable to this interface so that I have autocomplete on my editor?
I tried this:
const { data: todo }: Todo = res;
But the compiler complains: Property 'data' does not exist on type 'Todo'
I'm guessing I'm trying to cast the whole res
object to the interface Todo
, but I don't know how to keep the destructuring+renaming of the data
property wile casting it to an interface