Type inference
The very first thing I want you to understand is type inference. You do not need
to type everything. Some types can be inferred by TypeScript.
Imagine a situation where I have told you, "I have put only chocolate donuts in
the box on your desk." Since, in this example, I pretend to be the computer, you
can trust me. Hence, when you arrive at your desk, you are 100% sure that the
box is of the sox type. You know this without opening the box or
having an explicit sticker on it that says Box full of chocolate donuts.
In a real code, it works very similarly. Let's look at the following minimal
example:
const sonevar = 123; // someVar type is number
This is trivial. We can now look at something that I like more, chocolatevonuts, aS
follows:
enum FLAVOURS {
CHOCOLATE = ‘chocolate’,
VANILLA = 'Vanilla',
3
type Chocolatebonut = { flavour: FLAVOURS.CHOCOLATE }
const clone = (sth:T):T => JSON.parse(JSON,stringify(sth) );
const produceBox: (recipe: T) => T[] = (recipe: T) => [
yz, iamrectne), lone(eecipe), elone(recipe)
// box type is inferred
const box = produceBox({ flavour: flavours CHOCOLATE });
W/ inferred type correctly contains flavor key within donut object
for (const donut of box) {
console. log( donut. flavour);
}// compiles and when run prints "chocolate" three times
In this example, we exercise both the enus and generic types. The c1one simply
clones any type into a brand new one and delegates to JSON functions: stringity
and then parse. The eroducetox function simply takes a recipe and creates an array
of clones based on that recipe. In the end, we create a box of chocolate donuts.
The type is correctly inferred because we have specified a generic type for