DEV Community

Discussion on: 4 Must-Know TypeScript Tips & Tricks

Collapse
 
sam_piggott profile image
Sam Piggott • Edited

Hey Vetras! It doesn't actually rename those properties - rather, it plucks them from the original interface and creates a new type consisting of the picked properties. So in that case, the resolved Pizza type would end up looking like:

type Pizza = {
    caloriesPerServing: number;
    size: "large" | "medium" | "small";
}
Enter fullscreen mode Exit fullscreen mode

Hope that makes sense :)

Collapse
 
vetras profile image
vetras

sorry :) I might have explained myself wrong.
I meant; What if you rename the size property to count, for example.
Would the Pizza be renamed to pizza.count?
Can the IDE pick that up? (pun intended 😎)

Thread Thread
 
sam_piggott profile image
Sam Piggott • Edited

I guess if you wanted to add count to the new type, could you do something like so:

interface Pizza extends Pick<Consumable, "size" | "caloriesPerServing"> {
    count: number;
}
Enter fullscreen mode Exit fullscreen mode

That way, you'd get size, caloriesPerServing and count as properties on the Pizza type?

Unsure if that's what you're asking, but I hope that helps!

Thread Thread
 
vetras profile image
vetras • Edited

true. that is not what I meant. I mean renaming the original property named "size" to the new name "count" (as an example).

Refactoring is a big part of writing maintainable software and renaming is a basic corner stone of refactoring.
Hence my question.

Thread Thread
 
sam_piggott profile image
Sam Piggott

I think I understand - so you're suggesting if we renamed size to count, this would cause issues?

Type-checking would catch that (the beauty of TypeScript!). In the below example, we pick the two properties to create the new Pizza type...


type Pizza = Pick<Consumable, "size" | "caloriesPerServing">;

const pepperoniPizza: Pizza = {
    size: "large",
    caloriesPerServing: 500
}

Enter fullscreen mode Exit fullscreen mode

But if we renamed "size" to "count", as you suggested...


type Pizza = Pick<Consumable, "size" | "caloriesPerServing">;

const pepperoniPizza: Pizza = {
    count: "large",
    caloriesPerServing: 500
}

Enter fullscreen mode Exit fullscreen mode

Then we would receive a type error at compile time on the pepperoniPizza declaration line, as the object's shape (Pizza) does not have the property count.

We could then perform the changes we require on our type:

type Pizza = Pick<Consumable, "count" | "caloriesPerServing">;
Enter fullscreen mode Exit fullscreen mode

...which would resolve the issue.

Did that make sense? Hope that answers your question!

Thread Thread
 
vetras profile image
vetras

Did that make sense?

yes it does

Hope that answers your question!!

yes it does

thanks!

Thread Thread
 
sam_piggott profile image
Sam Piggott

Ah, that's great to hear. Sorry I misunderstood you initially! :)