-
Notifications
You must be signed in to change notification settings - Fork 0
Typing Pizza App part 6
Even though TypeScript offers a good type inference on primitive or complext types, as part of good practices it's always good to manually declare those types.
If we check our menu variable declaration for example, type script is infering that menu is an array of objects, but not which is the type of those objects.
It's important to note that, even though the objects added to menu conform to the type Pizza, they are not really Pizza types - and this can be really seen if we change the Pizza type by adding the id property to it.
What happens when we add the id property to our code, like in the snippet below?
type Pizza = {
id: number;
name: string;
price: number;
};-
menudoes not have any problems with type checking, because it does not have a type defined as an array of pizzas - Other parts of the code where the pizza type is being used will start complaning about the missing property
To fix the first problem, all we need to do is to set the correct type for menu as Pizza[], like so:
const menu: Pizza[] = [
{
name: 'Margherita',
price: 8,
},
{
name: 'Pepperoni',
price: 10,
},
{
name: 'Hawaiian',
price: 10,
},
{
name: 'Veggie',
price: 9,
},
];This will now lead us to the second part, where no id property is given by any Pizza type variables in our application.
For now, to fix temporarily this issue, we are going to set manually the id property to every pizza object which is showing the warning where the id porperty is missing.
Those notes were written while watching the tutorial videos while taking the classes from the online course Learn TypeScript on Scrimba.
Because english is not my mother language, they can contain some typos and everything written here is based on my understanding about the discussed topics and may not be 100% accurate.
If you want the full course, support the instructor by buying their course on Scrimba.
- Home
- Introduction
- Introduction to TypeScript
- The Pizza Application
- Move to TypeScript
- Defensive Coding
- Typing variables
- Typing Pizza App: part 1
- Custom types
- Typing Pizza App: part 2
- Nested Object types
- Optional Properties
- Typing Pizza App: part 3
- Array Types
- Typing Pizza App: part 4
- Literal Types
- Unions
- Typing Pizza App: part 5
- Typing Pizza App: part 6
- Typing Pizza App: part 7
- Returning Types
- Typing Pizza App: part 8
- Any Type
- Typing Pizza App: part 9
- Utility Types
- Typing Pizza App: part 10
- Generics
- Typing Pizza App: part 11