Recently, I ran into a little issue while using TypeScript in a project. I was trying to pull out some values from an object, something I’ve done a bunch of times. But this time, I wanted to make sure those values were the right type.
Here’s what I started with:
const { title, pages } = bookDetails;
I thought I could just slap the types right in there like this:
const { title: string, pages: number } = bookDetails;
Turns out, that wasn’t right. TypeScript thought I was trying to rename title to string
and pages to number
, which wasn’t what I wanted.
The right way to do it is to put the types after the whole thing:
const { title, pages }: { title: string, pages: number } = bookDetails;
But then I found an even cooler way. If I make a type or interface first, like this:
interface BookDetails {
title: string;
pages: number;
}
I can keep it super simple when I pull out the values:
const book: Book = bookDetails;
This little adventure showed me that even when you think you know something, there’s always a twist or a new trick to learn, especially with TypeScript.