Afrikaans
Akan
Albanian
Amharic
Arabic
Armenian
Azerbaijani
Basque
Belarusian
Bemba
Bengali
Bihari
Bosnian
Breton
Bulgarian
Cambodian
Catalan
Cebuano
Cherokee
Chichewa
Chinese (Simplified)
Chinese (Traditional)
Corsican
Croatian
Czech
Danish
Dutch
English
Esperanto
Estonian
Ewe
Faroese
Filipino
Finnish
French
Frisian
Ga
Galician
Georgian
German
Greek
Guarani
Gujarati
Haitian Creole
Hausa
Hawaiian
Hebrew
Hindi
Hmong
Hungarian
Icelandic
Igbo
Indonesian
Interlingua
Irish
Italian
Japanese
Javanese
Kannada
Kazakh
Kinyarwanda
Kirundi
Kongo
Korean
Krio (Sierra Leone)
Kurdish
Kurdish (Soranî)
Kyrgyz
Laothian
Latin
Latvian
Lingala
Lithuanian
Lozi
Luganda
Luo
Luxembourgish
Macedonian
Malagasy
Malay
Malayalam
Maltese
Maori
Marathi
Mauritian Creole
Moldavian
Mongolian
Myanmar (Burmese)
Montenegrin
Nepali
Nigerian Pidgin
Northern Sotho
Norwegian
Norwegian (Nynorsk)
Occitan
Oriya
Oromo
Pashto
Persian
Polish
Portuguese (Brazil)
Portuguese (Portugal)
Punjabi
Quechua
Romanian
Romansh
Runyakitara
Russian
Samoan
Scots Gaelic
Serbian
Serbo-Croatian
Sesotho
Setswana
Seychellois Creole
Shona
Sindhi
Sinhalese
Slovak
Slovenian
Somali
Spanish
Spanish (Latin American)
Sundanese
Swahili
Swedish
Tajik
Tamil
Tatar
Telugu
Thai
Tigrinya
Tonga
Tshiluba
Tumbuka
Turkish
Turkmen
Twi
Uighur
Ukrainian
Urdu
Uzbek
Vietnamese
Welsh
Wolof
Xhosa
Yiddish
Yoruba
Zulu
John smilga teaches this course about
the Practical applications of typescript
typescript is a strongly typed
programming language that builds on
JavaScript this is an excellent course
for people who want to learn typescript
hey what's up it's John from coding anic
and welcome to practical typescript
course we all focus on practical
applications of typescript so you can
start using it effectively in your
projects right away during the course
we'll cover everything from setting up
your development environment to
deploying your typescript applications
the course consists of three major parts
first part typescript fundamentals where
we'll explore basic types interfaces
classes generics and rest of the good
stuff second part react and typescript
where we'll integrate typescript into
react projects create typed components
and manage state with typescript and the
third part
is where we'll put our typescript
knowledge to good use and build a modern
store application with typescript shat
UI and react router if you wish to
explore all of the features of the store
project it's located at this URL
typescript comy sloth ny. apppp again
the URL is typescript comy sloth ny.
apppp quick sign not during this video
will only cover Parts one and two so if
you enjoy the content and wish to work
on the big project as well consider
enrolling in the full Course located at
coding addict IO again the full course
is available at coding addict IO okay
and first let's recap that JavaScript is
considered Loosely or dynamically typed
because variable types are determined at
runtime and can change as the program
executes this means you don't have to
declare the type of the variable when
you create and variable can hold values
of different types at different times so
the following code is a valid JavaScript
code however where are we going to
encounter an error if we try to run this
code correct at runtime and this is
manageable if you have few lines of code
but the bigger the project the more
challenging it will be
to spot such technically innocent bugs
and this is where typescript enters the
picture because it is a programming
language that builds on JavaScript by
adding static typing this means you can
specify things like types of variables
function
parameters return values and some other
things to help catch errors early and
improve the code quality it is a super
set of JavaScript so yes all the
JavaScript code is also a valid
typescript code now one way to think
about it is as follows by using
typescript in our project we'll still
write the JavaScript we already know but
with some elements or sprinkles of
typescript and these elements will act
as safeguards or constraints to help us
catch potential errors more quickly and
without the need for 10,000 console logs
when we introduce typescript to our
project we will write our app in the TS
or in the case of react in the DSX file
there will be a compile or transpile
step where all of the typescript code is
transpiled to good old JavaScript code
and at the end since it is a vanilla
JavaScript code we can run it anywhere
quite often you'll hear people say
something along the lines of well once I
built my first project with typescript
it was very hard to go back and build
with just vanilla JS and even though I
was also very skeptical of such
statements I can verify that it was the
same in my case yes typescript still has
learning curve and yes it involves more
work but at the same time you'll notice
how how you're able to fix bunch of the
errors quickly at build time without
running around like a headless chicken
before we set up a brand new typescript
project I want to mention a few useful
things if you're confused about some
topic or simply want to research a
concept in more detail a good place to
start is typescript docs which are
located at typescript l.org again the
URL is typescript l.org also in there
under the playground tab you will find a
Nifty code sandbox or typescript
playground which I might utilize from
time to time during the course to
underscore some particular point it
works as follows on the left side we
write a valid typescript code and we get
back the resulting JavaScript code now
you won't be able to build the entire
project in there but it is a very cool
option if you you quickly want to test
something as far as the code editor I'm
going to use VSS code and since it's
practically an industry standard these
days my assumption is that you'll use
the same one since I record courses I
use the very basic default theme and
when it comes to my extensions I will
mention some useful ones once there is a
need during the course in order to work
with typescript you will need no
installed on your machine again
something I assume you already have done
but if it's not the case please visit
nodejs.org again the URL is nodejs.org
pick your operating system and follow
the install steps also during the course
I'm going to reference the main course
repo where you'll find source code
challenges notes useful references and
tons of other useful stuff so I highly
suggest getting a hold of the repo
before you continue with the videos just
look for my GitHub profile and under the
repos search for typescript course
repository there are few ways how we can
add typescript to our project since it's
available as an npm package we can
install it globally or on the per
project basis set up the configuration
and run the compile step manually the
this is definitely an option but we're
going to take a different approach which
is going to
be pre-built template because at this
point at least in my opinion it's a more
realistic scenario chances are whether
you want to build a nextjs or remix or a
good old react app there will be already
a template that contains the technology
you want to use as well as types
configuration so more often than not
your job will be to write a valid code
instead of losing your sleep over
correct configuration setup for this
course I picked V since it's one of the
most popular build tools out there but
please keep in mind as far as the
typescript logic is concerned it's the
same if for example you're going to use
nextjs with a typescript template now we
want to run one command in order to set
up our template and I'll show you two
places where you can get the command
First Option you can navigate to V docs
which are located at bejs
dodev then click on getting started and
pretty much you're looking for this
command and then we just need to pick
the template and since my npm version is
bigger than seven I'm going to run my
command with the Double
Dash now as you can see we have tons of
templates available and the idea is
following we go with npm create V latest
then project name then Double
Dash go with the template one and pick
the template as you can see we can go
with reacts as a say not something we're
going to use in the part two and three
we can also for example set up The View
with typescript and we're actually going
to start the course with vanilla
typescript template so this is just
going to be an application built with
vanilla JavaScript we're not going to
use react and uh to tell you honestly we
don't really care about the template we
just want to use it in order to learn
typescript so pretty much most of the
first part of the course will spend in
one file and you'll see what I'm talking
about in a second now remember in the
previous video I mentioned the main
course
repo navigate over here and then look
for typescript tutorial and under this
directory look for read me and here
you'll right away get the command and as
a this is something that I'm going to
copy in literally a few minutes and I
suggest actually doing the same because
in here again you'll find find all of
the notes and challenges and all that
cool stuff so if you want to save
yourself time on typing just navigate
over here and grab the command again npm
create V at latest then at least in my
case the project name is going to be
typescript then double dashes then
template and we're going to go with
vanilla DS so let me grab the
command let me navigate I guess to
desktop and and I'm going to zoom
in then let me set up my
command and once I have successfully
installed the project on my machine I
want to open up my text
error drag and drop the folder and next
we'll take a look at the files and
folders available in this template as
far as the files and folders we've got
over here a public one so this is where
we can place the public assets then we
have a S one essentially this is where
we'll do all of our work a get ignore
where we specify which files are going
to be ignored by The Source control then
index HTML which is actually going to be
our homepage also a package Json
something we're going to cover in more
detail in a few minutes and also a TS
config which we'll cover in Greater
detail later on in the course and before
we take a look at the specific
files and cover the build step here are
a few things I want to do first since
it's a node application we do want to
install the dependencies so effectively
just open up the integrated terminal and
run npm install now also again I highly
suggest getting the readme since in my
opinion you will find find it super
useful as you're following
along so just navigate back to the
project and somewhere create a read me
markdown one and just paste the contents
over here save it and once we install
dependencies now we also get the node
modules so this is where all of our
dependencies are located then we want to
go with npm run Tav which is going to
spin up our project in local development
and we're looking for Local Host
5173 and this is what we should see on
the screen so essentially there's some
images over here a text as well as the
counter now if I'm being perfectly
honest like I mentioned previously we
really don't care about the actual
vanilla JS application I believe towards
the end of the first part of the course
yes we will build a tiny app but most of
our time we'll spend over here in a
source one in one specific file called
tutorial DS where effectively we will
just learn all the typescript
fundamentals now if we take a look at
the package Json we see that we have the
dev one this is the command we just
invoked and also there's a build one now
before we run
build I do want to create a file and
showcase how our setup is going to look
like now one interesting thing that I do
want to point out notice how before the
build command they actually invoke
tsnc so notice how typescript is a Dev
dependency so before the project is
built first it's compiled so that's the
step I mentioned previously where we're
going to write all of our code in the
files with Ds extension and once we
perform the build step it's going to
spit out the vanilla JavaScript code so
if we take a look at the index HTML like
I said this will be our homepage so for
example if you want to change the title
it's definitely an option then they have
over here this div with an ID of app and
effectively in a second you'll see how
in the main DS they in
Jack the images the divs and all that
into this app one so now let's navigate
to the main DS in here they import
styles again something we're not really
concerned with also two images the
typescript one and V1 and also a counter
and then they
select div with an ID of app and like I
said they dynamically inject the
elements into the d as you can see there
are some already sprinkles of typescript
and essentially this is something that
we're going to cover during the first
part of the course but most of the logic
should look very familiar correct
because this is straight up JavaScript
again with just sprinkles of typescript
now if we take a look at the counter
it's going to be same idea this is
straight up JavaScript with the only
difference that now we're looking for
element and actually we specifically say
that the type is going to be HTML button
element now how is our setup going to
look like since I said that I mean we
really don't care about this code and to
tell you honestly we're not actually
going to look too much in a browser
either most of the time will spend in
the error well in here in the source I
want to create a new file in my case I'm
going to call this tutorial TS the name
is totally up to you just make sure that
you add the TS extension so we're going
to go over here with tutorial then TS we
create a new file and for now I just
want to log just so I can see that
everything works and I'm going to go
with typescript and then tutorial let me
save it and then in order for this code
to run we just want to navigate to Main
TS and we just want to import a file
that's it we're not going to do anything
else we'll simply go with import and now
we're just looking for our TS file so
tutorial and TS and the moment we do
that once we navigate to the browser if
everything is correct we should see that
console
log and if that's the case we are in
good shape and before we move on to
typescript fundamentals let me show you
the result of the build step again let's
just recall that before V our build tool
builds the production ready application
it's actually going to compile our code
which essentially just means that all of
the typescript elements we're going to
have in our code are going to be
transpiled to good old vanilla
JavaScript and essentially during this
video I just want to showcase that so
don't worry about the code I'm going to
write in fact you don't have to follow
along I just want to showcase the end
result so let's say if we're going to
add something typescript for example
interface of course something we're
going to cover during the first part of
the course and I'm going to go with name
String and ID number and as a sign note
essentially it's just a shape of an
object and then I'm going to create the
object and I'm going to go with some
value so add the type over here and now
I just need to provide name which has to
be a string now so I'm just going to go
with random and comma and then we're
going to go with ID and then one two 3
and then let's also log so let's go with
some object so once we navigate right
now to a terminal we have few options if
you want you can always stop the dev
server and essentially you do that with
contrl C or you can just open up a new
terminal window and that is going to be
my Approach so essentially now I want to
go with npm and not Dev but we're
actually looking for build so we run
this command if we don't have any
typescript
errors we're going to be successful and
now notice we have this this folder so
this is our production ready application
we still have index HTML okay everything
is beautiful and then in the assets
we'll have the index JS so this is
essentially our application in vanilla
JS and if we take a look at our code so
notice I have this console log
typescript tutorial so I clearly know
that it's coming from our file notice
there is no interface anymore again
there is some kind of minified object
over here and effectively we also conso
log it that's it so there is no
interface there is no type string or
type number or in fact any of the other
stuff that we have here as far as the
typescript elements so again essentially
we'll write all of our logic in files
with Ds or DSX extension if we're
working with react and then once we
build our project
we're going to get back our good old
vanilla JavaScript code which
essentially we can run anywhere so
hopefully it's clear what's happening
during the build process so now let me
clean up our project first I want to
remove the disc folder then also I'm
going to remove my second terminal
window and at the very end I just want
to remove this code from tutorial yes so
this is going to be our starting point
essentially we have console log in
tutorial DS and if we take a look at the
browser we should see over here
typescript tutorial and if you have the
same result now we can move on to the
next task okay and let's start our
typescript journey by discussing type
annotations which allow us to
specify the variable type so let's say
in my project I have a variable by the
name of awesome name and if you have
watched any of my courses and tutorials
you know that the most awesome name ever
is shake and B since I'm working in a
typescript project I can actually
explicitly set up the type and the
syntax is following we go with colon and
then since I want this to be a string I
type string now there are quite a few
types and I'm not going to list all of
them I really find it pointless
essentially the most straightforward
ones are string number and Boolean and
again the syntax is going to be the same
so we just go over here with the colon
and then the type and of course as we're
working through the course we'll get to
know the other types as well and the
moment I set this type for my
variable I get two things out of the box
essentially it can never be something
something else so I can go to the next
line and set it equal to a function and
also I'll WR way get the methods that
are associated with this type so in this
case it's going to be a string so just
to demonstrate that if I go to the next
line and if I set it equal to a value of
something this is still valid why well
because type is string so everything's
correct correct also I can go to next
line and set it equal to awesome Dot and
notice right away I get only the methods
that are
associated with the typ string which
again is super awesome because
essentially I avoid some unnecessary
bugs so in this case I'm just going to
go to application and now if I log this
value if I go with awesome name and take
a look at my console if everything is
correct should be equal to a something
so we set it equal to different string
value and then we ran the two uppercase
method now one thing we canot do is
something like this where I go with
awesome name and set it equal to 20
which is a different type so notice
immediately typescript starts yelling at
me type number is not assignable to a
type string and I want to repeat the
same thing for the number as well as the
bullion so just so it's clear we're
going to start with some kind of
variable in my case I'm going to go with
amount I'll set it equal to a number and
again I can do anything that's allowed
with the numbers for example and set
equal
amount 12 minus 1 something like that
but cannot set amount equal to pens
that's not going to work right away
typescript is going to be super helpful
it's going to say Hey listen you said
this is going to be the number so yeah
you can run the number methods you can
do calculations but you cannot just
reassign it to something else lastly
let's take a look at the Boolean pretty
much same
deal we're going to go with is awesome
we're going to add a colon set up a
Boolean type for Star it's going to be
true then we're going to set is awesome
equal to false and then let's try to set
it equal to shake and bake again the
most awesome name ever so we're going to
go with is
awesome and let's go with shake and bake
again cannot do it because the type is
bulling and essentially in the process
we're just avoiding this entire
debacle where initially it can be one
value then three lines later it's
something else and then we're turning
into a third thing and then start
running some methods on it
essentially this is static so now we say
Hey listen this is going to be string
and string only same goes for number
Boolean and in the process we just avoid
bunch of unnecessary bugs that come from
typos that come from just using wrong
methods and that sort of thing and
before we work on our first challenge
let me quickly mention something
typescript is actually really smart and
can infer the type of the variable based
on the values when it's defined now the
fancy name is type inference but
essentially for us it just means that we
can remove all of these type annotations
and we'll still get all of the goodies
that I covered in a previous video so
now if I hover over the awesome name
notice how based on the value when the
variable was defined typescript can
nicely infer the type so in this case
it's string then it's the amount and
then when it comes to is awesome
typescript knows that it's a Boolean now
don't dismiss the type annotations we're
still going to use them but most likely
not for such straightforward variables
type inference also has some gotas
especially when we start working with
more complex values so yes typescript is
always going to try to help you when it
comes to functions when it comes to
variables it will try to kind of get the
type based on the value and obviously
it's super awesome because it saves us
time notice I don't have to go to Every
variable and just make sure that the
type is set but there are some
questiones we need to aware of and don't
dismiss type annotations because we're
still going to use them throughout the
course just not four variables like this
okay and now it's time for our Challenge
and since it's our first one I will
cover the steps as well but with the
future challenges just so we can save
little bit of time I will most likely
right away start working on the solution
also since it's our first one it's going
to be extremely
straightforward I just wanted to get the
ball rolling just so we get used to this
idea that we learn some stuff and then
we work on some kind of challenge so I
want you to create a variable of type
string and try to invoke a string method
on it then same is going to be with a
number create a variable and try to
perform a math operation also I want you
to create the Boolean one and perform
The Logical
operation and then try to just assign
some values to those
variables that are different types so
just try to come up with something that
shouldn't supposed to work and see
whether typescript complains about it
now you can use the type adaptation or
you can also use the type inference
that's totally up to you again super
straightforward challenge where just
want to navigate to tutorial I want to
come up with some kind of variable for
my string in my case I will use the type
annotation don't ask me why just think
that it's going to be better in this
case so I'm going to go with hello and
then let's go with
typescript okay beautiful then let's run
the two oper case so greeting is equal
to greeting dot then two uppercase let's
invoke this this should work we should
have no issues and as long as I don't
have the red squiggly lines I'm good to
go so typescript is not yelling at me
then also let me set up the age so in
this case it's going to be a number I'm
going to set it equal to 25 then let me
add a five to it okay also works
everything is beautiful and then we want
to go with is adult so that's my Boolean
let's add a type annotation here AG is
let's say bigger or equal to 18 now this
should be true and you know this is the
case where I will log it so let's see is
adult is true yep that's the one so now
let me just set it equal to the opposite
I'm going to go with his adult is equal
to opposite is adult again let's log it
and now it's going to be false and and
then somewhere here let me just try to
set the greeing equal to 10 that
shouldn't work also we can go with age
and set it equal to 30 so string again
we're going to get the error and lastly
we have the is adult and I'm just going
to set it equal to yes and as you can
see all of them result in errors so
again we have one type and typescript is
not happy when we just randomly decide
that our variable is going to be of
different type all right and before we
continue with tutorial let me show you
something interesting about the setup
you see even though we have these
typescript errors over here we're going
to be able to run our project locally so
what am I talking about well if I go
here and set up the console and log and
in my case I'm just going to look for
all three values So reading age and is
adult if we navigate to a console you
can see first of all that all of the
variables have the values that they're
not supposed to so typescript is
complaining but it's still works and
also notice how our project didn't crash
we're just getting these typescript
errors correct so here's the deal when
we're working with typescript actually
project is going to work even with the
errors locally but whenever we want to
host a project what do we need to do
well we need to build it that's usually
the setup and in order to build it we'll
have to pass the typescript checks so if
we try to build with typescript errors
we're going to fail and as a result we
won't be able to host the project let me
show you the package Json notice over
here
so we have Dev command which essentially
just spins up the dev server and we also
have the build command and remember
before we even run feed build we
actually compile this with typescript
and again if we have some errors we
won't get the I believe it was this
folder where we have the static assets
which in turn are going to be used to
host our project so let me showcase that
just so we are on the same page first I
want to stop the dev server let me run
npm run build so at the moment I have
the errors typescript errors and
immediately I just get back these error
messages in my console so in order to
fix it what do we need to do well in
this case it's sort of simple where can
just comment them out delete them
whatever doesn't really matter again let
me clear everything
here let me run the last one npm run
build and now since I don't have any
typescript errors notice I have the this
folder and this is where I have my
production ready application so again
locally even with typescript errors
you'll be able to run the project
however you have some issues once it's
time to to deploy it once it's time to
build the production ready application
and up next let me introduce you to a
union type which allows a variable to
hold a value of multiple distinct types
for now we're just going to take a look
at some basic examples but since Union
types are super powerful it's not the
only time you'll see them in the course
so once we start working with functions
or and all that yep we're going to use
the union type as well so let's imagine
I have a variable by the name of tax and
typically it's a number correct so I can
set it equal to
10 typescript can nicely infer the type
and I'm good to go but let's imagine
that whether I'm getting it from the API
or whether user provides that value it
can also be a string I can go here set
up my colon then go with number so it
will definitely be a number and I can
use this pipe operator and then I can
just add another type which in my case
is going to be string now please keep in
mind you can add 10 another types but I
mean in our case we're just going to
stick with two but yeah you can go here
and add for example Boolean it's
definitely an OP option so now I can go
to a next line and I can set it equal to
a 100 and typescript is not going to
complain because yeah one of the types
is actually number now I can also go
here and set it equal to a string and in
my case I'm going to go
with uh let's go with $10 over here so
both of them are valid because now I
have Union type where it can be either a
number or a string now once we start
working with more complex examples yes
we'll have to do some checks and all
that so all of that is coming up but
this is a super powerful concept where
essentially we can say to typescript hey
this is going to be either this or it's
going to be the another type now also
something that I was blown away is the
fact that we can set up the literal
value type so that's the fancy name
essentially it just means that I can
provide the literal
values let's imagine we have a
request status so that's my variable now
what are the typical values for the
request status well quite often it's
pending success and error so for
starters I can just go here with pending
so that will be my initial value then go
with the colon and now I can just
provide the potential string values
which are going to be pending then again
I use the pipe
operator I provide success then another
pipe and I'm going to go with error and
what's super super cool is the fact that
whenever I work with this request status
notice I right away get these
suggestions so it can either be error
pending or success and
again it helps me to avoid errors
because it's way harder to mistype
something and also I kind of just go
here and say random I mean first of all
it doesn't match my suggestions and
second right away typescript is going to
complain so I don't have to find doubt
about this bug in the runtime I actually
can see it right away as I'm building
the project so let me go here with
success error is going to work so
there's nothing wrong with that but if
I'll try to set it equal to random as
you just saw I mean typescript is not
going to be happy about it topic we're
going to come back to when we set up
more complex examples and again Union
types allow us to set up multiple types
for the same variable and while we're
still in a roll let's also cover type
any which allows us to opt out of the
type checking so I'm going to create a
variable and I'm going to name it not
sure so not sure now I will set it equal
to four and since we already covered
that typescript can infert a Type we'll
see over here this number but I can also
go with colon and set up any over here
now any means exactly what the name
implies this going to be anything I can
set it up equal to function string
Boolean whatever so in next line can say
you know what not sure is actually going
to be a string maybe a string instead
then on next line I can set it equal to
false and as you can see that script is
not
complaining now as you're looking at it
probably the first thought is well wait
a minute that's
how variables behave in JavaScript and
you're absolutely absolutely correct now
as with everything in programming
there's bunch of fights over it whether
you should use any at all as far as my
two sents be very careful when you
introduce any to your
application because it can spread like
wildfire so you started off with setting
up one variable type any and then next
thing you know you have any all over
your application because for example
when you return any from the function
then the result is any and on and on and
on and on so definitely have a good
reason why you want to use any and as I
note any is something you'll see quite
often when typescript is trying to come
up with a type but we haven't provided
any clues for example if I'm just going
to go with some random and I'm not going
to set up the value as you hover over it
notice now this is going to be type any
so this is something we quite often get
by default when typescript is trying to
get the type but I mean I haven't
provided any clues what this value is
going to be and this is essentially
something that we'll constantly try to
fix where for example for functions
implicitly it starts with any but we
don't want it to be any we want it to be
some kind of type so just be careful
when you use it it's definitely an
option it's useful if let's say you want
to test something it's also useful if
you have a pretty big codebase and you
just slowly want to introduce typescript
so you still want to run the project but
you slowly want to add it to your
project yeah it's definitely the case
just again be very mindful when you set
something any because next thing you
know it half of the application is going
to be any and then at that point I mean
it kind of loses the sense to use the
typescript in the first place again
those are just my two scents if you go
to Google you'll find definitely way
stronger opinions but let's just leave
it at that and let's move on to the next
topic and next let's see a practical
application of type annotation where
essentially I have a list of books so I
just have some strings over here and I
also have a variable which at the moment
is undefined and there's no type since
again I want to showcase what type is
going to be set by default and I want to
set up a loop where I iterate over and
then if it matches one of these titles
over here then I'll set the variable
Found book equal to that title so first
let's set up the loop I'm going to go
with four off Loop so lead book off
books then we're going to set up the
condition so if book and I think I'm
going to go with the
first string over here so I'm going to
go with 1984 if that's the case then
phone book is going to be equal to a
book and we're also going to break out
so let's add the break keyword let's
save it if everything is correct this
should be equal to a title so we can
actually go with log and then found
book let's take a look at the console
yep we are good to go now everything is
awesome but let's take a look at the
type we have over here by default it's
actually set to
any which leads to problems because
anywhere whether that is in the loop or
over here I can do something like this I
can set it actually equal to 10 so
typescript is not stopping me and this
is the behavior which I don't want
because I actually want it to be a
string otherwise yeah in here it's going
to be a string if I'm successful inside
of this Loop but then eventually it
might turn into a function again good
old JavaScript variable Behavior but I
don't want this I want this to be a
typescript project where I explicitly
know what is the type so what's the
solution well we can navigate back over
here and and we can set it equal to a
string but now we have another problem
so let me remove these console logs how
do we know that for sure it's going to
be a string because keep in mind this
runs when at runtime so if let's say I
set it equal to
1983 well this Found book is not going
to be equal to a book what is it going
to be equal to well remember by default
variable are what undefined so if you'll
try to set up some kind of logic over
here assuming that it's a string
typescript is going to yell at you it's
going to say Hey listen you are using it
before there's even any kind of value
because again typescript is not going to
check whether at the runtime this will
be equal to a book so yeah we can set up
the logic over here where I can say if
for
sure the Found book is equal to a book
typescript knows that actually these are
strings so we can run the method on it
for example again let's go with length
so this is going to work but we cannot
do it outside of the loop because in
here there's no guarantee that actually
this will be a string so we need to set
up the union type where I'm going to go
with okay it potentially could be a
string but by default actually it is
undefined so it's another type that we
can use so now by default it's going to
be undefined if we're successful it's
going to be equal to a string and what's
super super super awesome is the fact
that typescript is going to be extremely
helpful where if you try to again go
with the good old length notice how it
will immediately add this optional
chaining why well because it can be
undefined and we can see that if we take
a look at the error message if you just
added dot notice Found book possibly can
be undefined and therefore typescript is
going to add that optional chaining so
now we only run this length if it's
actually equal to a string if we have
some kind of value so if we won't be
able to find a book which is the current
case then this actually won't trigger
the runtime error now if we're
successful then we'll be able to nicely
see the length of the book you know what
I will change this one around I'm just
going to go here to Found
book and set it equal to uppercase let
me do it this way so we're going for
uppercase let's invoke that and then
this one I'll just log it again it
really depends whether we're able to
find the book or no so now let me move
this pH book set it up here in my my
console and let's see what is going to
be the result so I'm going to navigate
over here if everything is correct I'm
going to get my four if I'm not
successful then essentially it's just
going to be undefined but I won't have
that runtime error where I'm trying to
access the property on undefined
hopefully that is clear okay and before
we move on to the next topic let's work
on a small Union type challenge where
first we want to create the order status
and in there we'll set up the literal
types and also we want to set up the
discount which can be a number or string
type and you know what just because I
like to break the rules I'm going to
start with the second one doesn't really
matter I'm going to go with number or
string by default I'll set it equal to
20 or any other number value and I also
want to test it whether I can set it
equal to
20% now this works but if I'll try to
set up discount equal to True
essentially a Boolean typescript will
yell at me which is exactly what we
expected and also let's set up that
order status so order status variable by
default is going to be equal to
processing but we want to set up those
literal types so this variable can be
only one of these values so we're going
to start with processing then we'll set
up our pipe and we're going to go with
shipped and also we want to add
delivered over here so now we can go to
the next line set it equal to one of
these ones and everything is going to
work but if I'll try to set it equal to
canceled again typescript will yell at
me so let me just set this one up
quickly where if we go with order status
I just decide that I'm going to pass
this value over here not going to be
successful since I can see this red
squiggly line let me comment this one
out we're done with the challenge and up
next we're going to discuss arrays in
tapescript and as far as the arrays in
typescript the general idea is following
let's say I have prices array and it's
all numbers so we're going to go over
here with 100 75 and then 42 if I want
to set up the type which is something I
want to
do again same deal we go with colon then
we go with type in this case number and
then we set up the square brackets so
now I'm essentially telling typescript
that this array will only have numbers
so if I had a number 34 everything is
fine if file tried to stick hello I'm
going to get the error because this one
is type string and I
explicitly told typescript that this is
actually going to be an array of numbers
and the same is going to work if I will
try to invoke push so if I'll try to add
the item number is fine string will
cause the error so let me comment this
one out the same works with string array
let's say we have
fruit and this is going to be equal to
apple and orange we want to set up the
type over here in this case it's going
to be a string and the same rules apply
if we try to add the item that doesn't
match type we get the red squiggly line
now be careful with the empty square
brackets so if we go here and just come
up with random
values and set it equal to empty square
bracket so if we won't provide the type
over here typ script just assumes that
this will always always be an empty
array so if I set it equal to my array
and start adding items typescript will
immediately complain and notice as we
hover it says well type string is not
assignable to an Mt right so be careful
with this one I know it's temp thing
also be careful when you don't
explicitly set up the type so if I were
to create an empty values
array typescript will get the type but
check it out now the type is any so just
like before we'll run into those issues
because now we can change these values
any way we want so we can take the
string then it turns into a number and
same deal so be careful yes
typescript will infer the type but most
likely you don't want to set it equal to
any so this is the case where we want to
create the MD but we explicitly want to
say yeah this is going to be type number
or string or Boolean or whatever now
also while we're still on a subject of
typescript inferring the type let's take
a look at this example let's say I have
the names array and I have over here
Peter and Susan so if we hover over the
names everything is correct typescript
sees that we have over here a list of
strings and it correctly says the type
for this array is string but here's the
gotcha since typescript is inferring
those values based on what we have over
here in the array it doesn't stop me
from doing this and now if we hover over
it we can see that actually we have this
Union type like I said we'll be coming
back to this topic and now we have
string or number so essentially now I
can add numbers as well therefore be
careful when you're relying 100% on
typescript to set the type it's not
going to stop you from adding different
values to the particular array and in
that case well the type also is going to
change now we can explicitly set up the
array to be one or the other type so I
can go with array for example and I can
say that you know what this array is
going to have either string or a
Boolean again we still set up the square
brackets over here and we set it equal
to an array where we set up those two
values so we can go with Apple
then true which is a Boolean and the
same deal orange and let's set the false
one over here and with this in place we
can start working on our next challenge
okay and once we're familiar with arrays
now let's work on a tiny challenge where
we want to set up the temperatures array
which will be type number and colors
which is going to be type string and
then we also want to set up the mixed
array so let's start with temperatures
essentially our array of numbers now
this one
probably is going to be the hardest as
far as the spelling yep notice over
here me fix that one okay good that took
a while then I want to set up my type
number and we're going to set up 20 then
25 and then 30 and let's try to push I
don't know a string of hot so let's
actually
then go with push and let's try to pass
in the string and we won't be successful
so we can nicely comment this one out
after that we have colors
one so this will be actually type of
string and in here we're going to go
with red green and blue let's save it
and let's try to add a Boolean why not
so colors here dot then push and we're
looking for a bull and mow which is not
allowed and then let's set up the mixed
one so we're going to go with variable
in this case I'm going to call this
mixed array and this one will be either
a number or a string so number pipe and
we set up a string so let's set it equal
to our array and in here you know what
just to make it interesting why don't we
try to add true so bullan and notice
right away I'll have my error so let's
go with one then two and then we want to
add three and with this in place we can
move on to the next topic and up next
let's discuss object in typescript in
order to do that I'm going to create a
car and here I'm going to set up the
brand that one will be equal to a let's
say Toyota and also I'll set up the year
so first let me set up the string over
here and then let's go with year and
we'll set that one equal to a number and
if we want to set up the type annotation
it might look a little funky but we want
to do it this way we again we go with
colon then we go with curly braces and
then one by one we set up those
properties over here so I have a brand
and what is the type well it's going to
be string but also I have a year and
what is that one well that's a number so
again either if I try
to add some
property manually here where I'm setting
up the object or for example if I do it
dynamically by going card Dot and then
the property value unless this property
is in the type annotation it's not going
to work I think I'm just going to use
the color example so let's say I'll set
up the color and it's going to be equal
to Blue notice right away I have the
complaint because the property is not in
my type annotation and the same goes if
I go with car and brand yeah I can set
it equal to Ford since that's the
correct type but again if I go with car
and color it's not going to fly so
typescript will immediately complain now
if you're looking at it and you're
thinking to yourself well boy this is
super clunky over here I have this
object and then actually this is going
to be my type annotation don't worry
this is just essentially the most basic
setup but I wanted to cover it since I
wanted you to understand how everything
works under the hood but eventually we
will cover something called type aliases
where we will nicely be able to set up
this shape somewhere separately and
effectively just reuse the variable so
again you won't have this clunky code
most likely you won't use it but I
definitely wanted you to kind of see
this type of syntax so now once I have
my first car well I can create another
one in this case it's going to be a car
one since I'm already using the car
variable and then I'm going to go with a
different brand and also I'll change the
year and I don't think it's necessary
for me to repeat all of the steps
hopefully it's clear whatever we set up
in this type annotation needs to match
what we have in the object otherwise
typescript is not going to allow us to
compile essentially our code and now
let's tie two things together I want to
tie the arrays with the object and in
the process we'll also cover how we have
read only option with the typescript as
well as the optional properties so first
I want to create three objects I want to
create book pen and notebook and I want
to add them to the items array which by
default is going to be let's say empty
but we'll set up the types in a second
so first let's just go with items not
going to place anything inside of it and
then let's create those three variables
so in here we're looking for a book it's
going to have two things we're going to
go with title we'll set it equal to book
and we'll also have cost okay set it
equal to 20 and then I'll change this
one around to
pen
okay and the cost I mean again totally
relevant I'm going to set it equal to 10
I guess and then I want to go with
notebook but for Notebook actually want
to remove the cost and like I said now I
want to store all of these three values
over here in the items but here's the
kicker though I do want to make sure
that all of them have the same shape now
as we're looking at it we can clearly
see that it's not the case with the
notebook but let's imagine that we don't
know that and at this point we have two
options we can either repeat the same
steps like we did for the car so
effectively I can just set up this type
annotation for all three of them one by
one or since I have an array and I can
also set up the type for array I can do
it in one place where I have the items
so far we know that we can set up the
array to be equal to a string or a
number or a bullion correct and we also
cover the type Union but we can also do
something like this where I can say yeah
this is going to be an array of objects
and then each object needs to have this
particular shape now what is going to be
the shape I'll say title is equal to a
string or I'm sorry I don't know why I'm
placing this in the quotation marks and
then also I want to set up a cost so
we're going to go with cost and we'll
set it equal to a number and now one by
one as I'm adding these items to my
array once I get to a notebook check it
out now typescript is like Hey listen
this notebook that you're adding well
notice it only has the string it doesn't
have the cost so whatever type you set
up over here well it doesn't match so
again super useful where instead of
setting them one by one if we have an
array we can set it in one place because
we also can set up types for array now
what is the solution well technically we
can go back and add cost over here but
we also have this option of adding
optional properties now please keep in
mind you can use the same optional
property over here as well when you're
setting up the type annotation for an
object I'm just doing it here in Array
since this is where we're currently
working hopefully that is clear and now
I don't have the error because when I
set up the cost to be optional well it
could be there or it potentially could
be missing which is the case for a node
and what's also really interesting is
that with typescript we can set up the
properties to be read only again same
deal of course we can set it up over
here but in my case I'm going to do that
for the title where right before I set
up my property I'm going to go with read
only so now if I go with items and I
access let's say the first one here and
if I try to overwrite the value so dot
title is equal to a new book for example
it's not going to fly so now typescript
is immediately complaining that Hey
listen title is readon so you cannot
change this value over here so let me
comment this one out this concludes the
object fundamentals in typescript and
now we can start working on the next
challenge so now let's work on the
objects challenge where we want to set
up the bike we want to set up the laptop
then we'll create some products and
we're going to store it in the array so
let's start with our bike that will be
my object let me come up with some kind
of values over here then we also want to
add the
year and now let's set up our type
annotation so we're going to go with
colon then brand will be equal to string
and also we'll have the here and we'll
set it equal to a number that should do
it now we just want to change it to a
laptop so let me copy this
one change the name then brand stays
year stays we're just going to add a
different string value this case it's
going to be Dell and also change the
year and now let's see some errors so if
I'm going to go with bike and year and
set it equal to Old it's not going to
fly why well because year is set to be
equal to type number and same is going
to work if I'm going to create a second
laptop so I'm going to go with laptop 2
and it's only going to have a brand so
we're not going to have the year so if
I'm going to set it like this notice we
get our red squiggly which means that
there's some kind of error and now let's
set up those products so we're going to
go with product one that one is equal to
title let's go with
shirt and let's set up the
price that one will be equal to
820 then let's copy and paste we're
going to go with two this one will be
equal to a pants one why not pants are
awesome now we don't want the price so
we will need to set this one up as
optional and let's create the product
all right let's right away set up our
type by the way this was supposed to be
square brackets we want to go here with
title that one is equal to a string and
then also we want to go with price this
one will be optional and we'll set it
equal to a number so now in the array we
can nicely store product one and product
number two now it looks like typescript
is complaining why well because I forgot
the square brackets and at the very end
let me just showcase something
interesting where if I go with products
and then push
provide the object set up a title here
in my case I'm going to go with shes
even though price is optional we still
need to provide the correct type so
let's say if I don't provide anything
notice how typescript is not complaining
effectively this is optional
the price one now if I do provide the
price it has to be a number so if I go
here with price and set it equal to a
string T will immediately complain yes
it's optional but if I do decide to pass
the value the type needs to match
whatever I have here in the type
annotation beautiful we have finally
arrived at the functions in typescript
and I'm super excited to cover this
topic for a few reasons first our
examples are going to get more complex
because we'll start tying together all
of the concepts we covered previously
and also once we start working with
functions we absolutely have to start
using typescript and you'll see what I
mean in a second so let's say I have a
function of say hi why not let's set it
up say hi for now we're not going to
pass any parameters and as far as the
function logic we'll just leave it empty
now say high is looking for what well
probably some kind of name correct and
in a function body we can nicely log it
so the moment I type over here any
parameter in my case name notice right
away I'm getting these red squidly lines
and this is what I'm talking about at
this point we absolutely have to start
using typescript otherwise typescript
won't compile our code so if we hover
over we notice parameter name implicitly
has any type and essentially typescript
complains about it so that's not allowed
yes by default implicitly it's a set up
as any but we need to fix it in order
for typescript to compile our code and
at this point essentially we have three
options first we could set typ any
ourselves elves that's definitely one
option also and you know what let me
just comment this one out also we can
navigate to DS config and we can
actually change the configuration
something I'm going to Showcase in a
second or the best scenario is for us to
actually set this one up with a proper
type annotation so in this case I'm
looking for a string most likely so I'm
I'm going to say type okay so let's try
it out here with any what's the issue
here well just like we covered before
any is anything so everything that we
can do in JavaScript pretty much will be
able to do with the name here and
actually I believe in two videos I'll
showcase the any GOA that we need to be
aware of so this is not going to be
approach yes technically you can do it
but I mean at at this point we kind of
lose the benefits of typescript now
second option we can navigate over here
to the package Json or I'm sorry why am
I going to package Json we're going to
DS config and notice over here this
strict rule technically we can change it
around I can set it equal to false and
at that point typescript won't complain
about the fact that parameter by default
is left as any so you can definitely try
it out you can set it equal TOA and
you'll see that actually code Works
everything's fine but in my case I'm
going to skip that I'm just letting you
know that technically this is an option
so we have finally arrived at the option
we're going to use and that is setting
name explicitly to the type we're going
to use and just like before we simply
want to go with colon and we want to
come up with the type my case that is
going to be string and again I know
you're probably sick of this method but
I'm just going to use two uppercase
essentially I want to set up over here a
log then I'm going to go with template
string and we're going to go with hello
there over here and now I'm going to
access the name so the moment here we
set up a proper type let's say string
number or whatever two things are going
to happen first when we call this
function every time we'll pass in a
wrong type typescript is going to yell
at us and second within this function
body we can only perform functionality
that is allowed on this specific type so
in here yes let's go to uppercase let's
invoke it and let's try invoking say hi
and let's say I'm going to pass in John
and also in the next line I'm going to
pass in three so if everything is
correct we should get an error over here
we can nicely see that we can only grab
the string Methods inside of the
function body and if we inspect the
console we should see John over there
and lastly if we try to pass more
parameters than what we have specified
we'll also get an error and typescript
won't compile our code and with this in
place now we can move on to the next
topic okay and up next let's talk about
function returns so first I'm going to
create a function and I'm going to call
this
calculate
discount discount over here it's going
to be looking for price and I know that
that type is going to be number for now
inside of the function body I simply
want to go with the return and we're
going to go with price again since this
is a number once I press do notice I'm
only getting the methods that are
associated with the type number and if
you're sick of me hearing this I'm sorry
but I'm going to keep on repeating that
because again I find this truly helpful
and let's say I'm going to multiply this
by
0.9 so I'm going to go over here 0.9
okay good and then I'm going to set up a
variable so I'm going to go with cons
final price and I'm going to set it
equal to calculate discount I'm going to
pass in 200 and I don't think I need to
log the value I I don't think it's
necessary so if I hover over the final
price I can see that it's a number now
why is that a case because again
typescript is inferring the type
typescript says okay so this is a number
here we're returning a number multiplied
by something so whenever we hover over
this calculate discount we can nicely
see another set of colon and a number
over there and I know that it might look
a little funky over here but yes
essentially the syntax is following in
order for us to set up the type for the
function return we need to go after
parenthesis we need to set up the colon
and then we explicitly need to go with
the type now again you can make a case
well why do we need to set up type if
typescript is already inferring the type
well for essentially two reasons first
of all if I set up over here a number
type explicitly as I'm working in this
function if for some reason I forget to
set up the return or if I set up a
return which doesn't match what
typescript is expecting well I'm going
to get an error so it's going to be
super helpful let's Imagine This I have
some kind of has discount variable over
here and I'm going to just set up has
discount so essentially some kind of
condition and in here instead of
returning a number I'm going to go with
discount and applied notice right away
typescript is complaining type string is
not assignable to type number as we're
working in the function typescript is
kind of watching over us and if I return
something that I'm not expecting well
essentially typescript just starts
yelling at me because again yeah it's
trying to infer the type but once I
remove my logic well essentially now it
could be a string or it could be also a
number correct so now if we hover over
this notice we either have a number or
it's going to be discount applied and
the same goes over here either it
returns a number or discount applied so
even though it's technically optional
it's a good practice to set up the
return types explicitly since it helps
us tremendously as we're setting up the
functionality so now let me common this
one out and I'm just going to go with
price like so and with this in place now
we can move on to the next topic and
next I just want to show you why we want
to be careful with type any but this is
one of those videos where you don't have
to type along if you're not interested
essentially you can just sit back and
relax so let's imagine I have a function
and the name is add three so it's
looking for one parameter which is a
number and don't ask me why but I'm just
going to set it equal to any so I'm not
sure what would be the use case but
let's just go with it then inside of the
function body I'm going to create
another number in this case type will be
a number so I'm going to be explicit and
then as far as the return let's just go
with a return number plus another number
why not and then let's set up two
variables one is going to be result and
then we'll also set up some value so
let's try it out I'm going to go over
here with result that one is equal to
add three so as far as the value you
know what let me just pass in three so 3
+ 3 and then also we want to set up some
value so that one will be equal to a
result so now M Dar question and now I'm
not asking what is going to be the
result I'm more interested well what is
going to be the type so if we have our
over some value notice something
interesting
how essentially it's any and what that
means well go with some value and my
method and technically it's going to be
valid as I'm typing the code
but hopefully it's clear that it will
lead to some errors since there is no
method My Method and as you can see
everything starts with this innocent any
and notice how it trickles down so we
pass number that is type any and even
though this is a number and technically
this is a math operation typescript
should infer that we're returning a
number however if we hover over notice
over here we're expecting any we are
returning any so result is any then Su
value is any and as I mentioned before
be careful when you introduce any
because it can slowly trickle down or
spread like wildfire whichever term you
want to use and next thing you know it
you're going to be unintentionally or
intentionally running some methods or
setting up some kind of functionality
which doesn't make sense and at that
point you'll again need to start chasing
those bugs at runtime not as you're
writing the application so now if I
navigate to the browser notice over here
some value that my method is not a
function an error which which we can
expect since there is no such method on
some value and with this in place now we
can work on our next challenge beautiful
and once we're familiar with the
fundamentals let's work on our next
challenge and you know what I actually
changed my mind I will list out the
steps for a few reasons first the
challenges are getting more complex and
also I want everyone to be on the same
page let's say someone one is not
reading the readme or utilizing the
readme I still want them to kind of have
an idea what I'm trying to build so
effectively I want to create the array
names and then I want to write a
function that checks the name whether
it's in the array so this function
should take name as parameter and it
should return a Boolean whether the name
is in the array or not and then we want
to set up one or few checks and
essentially just test out some names so
let me go to my file first I want to
come up with a value and I'm going to
say that it's going to be an array of
strings and let's just provide some
random values so I'm going to go here
with John then I also want to go with
Jane let's set up Chim and also will
place a gill over there I don't know why
I said all of them starting with J must
have been a bad day in the office or
something like that then let's come up
with our function so in my case I'm
going to go with is name in list and
this function is going to be looking for
a parameter the type is going to be
string and I'll right away set up that I
want to return from this function a
Boolean so what
the name is in the array or not
therefore I'm going to set up my type
over here and then right away let's set
up the return I'm going to go with names
so that's the array and I'm just going
to use the includes method and in here
I'll pass in the name so I pass the
string over here and then I pass the
same one into includes and essentially
this is just going to return true or
false then let me set up a variable name
to check now technically I mean we don't
have to do it we can just pass it in but
you know what just to make things more
interesting I'm going to go with name to
check um in this case you know what I
will rely on the fact
that typescript will infer this type let
me type over here Jane and let me set up
if and else so I'm going to go with his
name in a list and I'm going to pass in
name to check that's the case I'll have
one log if not I'll have something else
so now let's set up those logs so in
here we're looking for a name to check
whatever it might be so now let me
access this as a variable so name to
check and then let's say in the list and
now pretty much let me just take the
same console
log and and add not in
list okay good and now let me save the
file let me navigate to the browser and
if everything is correct Jane is in the
list so if I'm going to set it up over
here a value of Peter now it's going to
say Peter is not on the list and with
this in place we're done with the
challenge and we're ready to move on to
our next topic and next let's discuss
optional and default parameters in
functions
essentially how we set them up from the
typescript
perspective I'm going to start by
creating a function
calculate
price it's going to look for two
variables price which is going to be
number and for now I'll set
discount as a normal parameter so I'm
not going to set it as default or
optional so let me go with discount let
me set it up as number then inside of
the function body I'm going to go with
return and we're going to look for Price
minus the discount okay good makes sense
I mean if we want we can set up over
here a number as a return as well that's
definitely an option and then let's go
with price after
discount and now will be equal to
calculate price and I'm going to pass in
some even numbers just so we don't need
to log it so essentially I pass in
100 as a price and20 as a discount and
then the result should be 80 all right
but what if I want to make this one
optional what if sometimes I'm going to
provide the value and sometimes well
it's not going to be available well the
syex is following we want to go to the
parameter and we need to add the
question mark but notice right away
typescript is
complaining and the reason for that is
because possibly discount can be
undefined and in our case we already
have a math operation where we take the
price and then we subtract a discount
but if this is undefined I mean it
doesn't make sense so the key thing to
remember about optional parameters is
that a function with optional parameters
must work when they're not supplied and
as far as the effects well we just need
to provide the fallback value so if this
is undefined the discount one well then
we'll have some kind of number value and
the way we do that we just set up the or
operator and in this case I'm going to
go with zero that's how we can work with
optional parameters in typescript and
while we're still on a topic let's also
discuss the default parameter now for
this one I think I'm going to create
another function why not let's just keep
on practicing this one is not going to
be calculate the price though we're
going to go with calculate score we're
going to pass in the initial score which
will be a number and also we're going to
go with penalty points and same deal for
now we're just going to set it that it's
actually a number I mean it will be a
number but we'll just set it as a
default eventually now as far as the
return again same deal we're going to
set it equal to a number and when it
comes to logic we want to go with return
initial score minus the penalty points
and once I have the function in place
now let me set up two variables so we're
looking for
score after penalty and I'll provide
over here calculate score and again I'm
going to go with with some even values
so I'm going to go with 12 and now I
want to set up another variable only in
this case I'm going to go with without
penalty and I'll just provide the first
one so that will be my initial score and
notice right away typescript is going to
complain so here's the deal if we set up
a parameter and we don't provide it or
we provide one too many
well then typescript will complain so
this is something to keep in mind and
how we can fix it well we can either go
back to this optional parameter which we
discussed in the previous video or we
provide some default for this one so we
make penalty points as a default
parameter and the way we do that just
like with JavaScript we just add the
equal sign over here and come up with
the value so in my case it's going to be
zero so now
if it's provided awesome we're going to
use the penalty points value if not well
then we'll just revert back to the zero
because that one is the default one and
here's the key difference if we use
optional parameter we do need to set up
this logic if we have a default one it's
not the case then we'll just use
whatever value is provided okay and up
next let's discuss how we can work with
rest parameters
in typescript and also let me showcase
one more time how smart the typescript
is let's say we have a function and the
name is going to be sum now for now I'm
not going to pass any parameters I'm not
going to set up any return type simply
want to have my function and I'm just
going to invoke it and show you what
arguments I'm going to provide so this
one will be equal to result and in here
I just invoke the sum and effectively in
here I want to provide two arguments so
I want to provide a string and a list of
numbers so string is going to say well
the total is and then whatever numbers I
provide they're going to be added
together and that will be my sum so in
here let me go with the string and let's
say
total is
then we're going to go with the colon
and then we have list of parameters so
this is where we'll need to implement
the rest parameter otherwise I mean one
case I might add five numbers in the
next instance it might be only three and
hopefully you see where I'm going with
this so it's not always going to be one
or two numbers it's going to be a list
of numbers so in this case I'm going to
go with one 2 3 four and five now
typescript is complaining since we
haven't set up those parameters over
here so let's start with a message in
this case it's going to be a string and
now let's see how it can work with such
list and essentially the syntax is
similar to JavaScript the only
difference is that we need to provide
well what type of array it's going to be
so in JavaScript we use this syntax
three dots then we come up with a name
in this case I'm going to go with
numbers over here and this is the rest
parameter and essentially JavaScript
treats this as an array so in here we
want to go with number because I need to
let typescript know what kind of type it
is and then the array now please keep in
mind if you have strings here as well
essentially you just go with number then
use the type Union and essentially set
up a string there as well and now pretty
much all of the arguments that are pass
the string are going to be collected in
this numbers array now I also right away
want to set up what are we returning
from this function and essentially it's
going to be a string now before we set
up the logic which we're going to do
with reduce I also want to showcase how
smart typescript is so I'm just going to
create
the doubled variable and I'm going to
set it equal to numbers so that's my
array then let's invoke map then we're
going to go with
num and let's just return num * 2 and
again let me just log I guess here just
so we can see that the functionality
works but one I want to showcase though
is this notice as we hover over
typescript immediately knows that it's a
number so let's say you have some kind
of call back function that you pass into
the map into the reduce and all that
that's is going to see what kind of type
array it is if you have supplied those
values and it will immediately know that
as we're iterating over this is a number
now you can explicitly provide the value
I mean no one is stopping you to go here
and say number but in general typescript
is super helpful and we also have right
away this useful error where the type
should be string as far as my return but
at the moment well I'm not returning
anything so let me set up that
functionality as well and this is the
case where I will use the reduce and
then I'm just going to return the
message the total is and then I'll sum
up the values so I'm going to go with
let total is equal two numbers then
let's provide reduce over here I mean we
can call this accumulator and total or
current however you want to do it in my
case I think I'm going to go with
previous over here and the current
one and then as far as the
logic side of the function let's just
return previous plus and then the
current one and the same deal typ knows
that it's a number since I have array of
numbers now since I'm using reduce I
also want to provide the default value
which is going to be null and then from
this function I want to return a string
so I'm going to set up the template
literal we'll provide the message and
we'll also provide the total over here
so now let me just see what the result
is I guess so let me just log the result
and also we should see that doubled one
in console so notice this functionality
works over here and the total is 15 and
in the process we cover two important
things how we can work with rest
parameter which essentially collects the
list of values if we don't want to
access them one by one and also how
smart typescript is in the Callback
function we don't need to explicitly say
well what type it's going to be
typescript already knows and up next
let's discuss what type we should return
if we're not returning anything from the
function and a good old example is just
having a console log so let me go with
function log message as far as the
parameter we're looking for a
message and that one will be equal to a
string and then in here let's use our
good old console log and let's just log
the message now I do want to invoke it
and I want to provide some kind of value
so in this case I'm going to go with
hello and typescript and since we have
nice suggestions if we just hover over
the log message we can see that
typescript inferred the return type as
void and void is a special type that
represents the absence of a value and
when we use it has a function return
type void indicates that the function
does not return a value now milon dollar
question do you always have to set it up
I mean it really depends on your
approach but it is super helpful
especially if you consider this once we
add this void over here even if I set up
some kind of return and I'm going to go
with hello world notice how typescript
right away says well you cannot assign
string to a void so if we decide that
this function is not going to return
anything and we set up the keyword even
if later on we mess up something and
start returning some values from the
function typescript is going to stop us
from doing that and up next let's
discuss Union types as function
parameters and what the typ guards are
now I did set up this topic as a
challenge just so you can see firsthand
the type of issues we will face so
here's the task I want you to create a
function called process input that
accepts a parameter of Union type so it
can either be a string or a number and
when it comes to
functionality if the input type is
number we simply want to multiply it and
log it in the console and if it's going
to be a string just use one of the
methods so in my case since my favorite
method is the uppercase one most likely
I'll use that one but it really comes
down to the preference so I'm going to
navigate to my tutorial and I want to
come up with a function so I'm going to
go with process and then input and I
believe in one of the previous videos
when we covered the rest parameter I
mentioned that you can still use the
union type I mean it's not a big deal
here I can go with input and then just
say string or the
number however once we set up the
functionality this is where we'll add
additional logic since now we have two
potential values correct so first let's
go with process input and pass in then
this should work and also let's pass in
the hello now what about the logic if we
simply log we should be good to go so if
I type input notice there are no issues
but now what if I want to multiply this
what if I want to say times two notice
immediately typescript is not happy why
well we have a type
string and we're multiplying this by two
now typescript doesn't know that in here
we passing in 10 and in here we have the
hello so we need to set up something
called type guard where before we do any
functionality we actually make sure that
the type is correct essentially if I
want to run a string method I want to
make sure that it's a string if I want
to multiply I want to make sure that
it's a number and again the fancy name
for that is typ guard now we you'll look
at multiple type guards the most
straightforward one is just type off
keyword and then we look for specific
value so inside of the function I do
want to set up a check so there's going
to be a condition and I'm going to go
with type off then I'm looking for my
parameter and I'm going to say if it's
equal to a number and notice how
immediately typescript was helpful and
provided bunch of options if you didn't
let me go back notice these are the
values that we can use and in this case
we're looking for the number if that's
the case what do I want to do well I'm
going to log times two over here now if
it's not the case typescript is also
smart it knows that listen if it's a
number we're going to do this
functionality what is the alternative
well the alternative it's a string
correct so in here we simply can go with
else then again we're going to go with
log
input and you know what just so people
are not upset with me I'm just going to
go with two
lowercase again the official name for
this one is type guard and we use it to
check the parameter at the runtime and
while we're still on a roll let's also
see how we can work with objects
as parameters in our function so I'm
going to set up a new function let me
call this
employ and in here I'll pass in the
object with the ID property and as a
side
note the second example which we're
going to cover is going to use a little
different syntax so in here essentially
I'm right away D structuring the ID I'm
saying yeah there's going to be an
object with the ID property and I right
away want to access it now as far as the
typescript same deal just like with
regular objects we want to set up this
type annotation and we want to be
specific well what are we're going to be
getting here so is this a number string
or whatever and in this case I'm going
to set it equal to a number as a side
note yes in like I believe three videos
we will cover typee aliases so it's not
going to be as clunky because at the
moment I fully understand if you're
looking at it and you're like whoa so I
understand this part but does that mean
that every time I'll have object with
like 10 properties we have to set it up
over here no there is a better solution
and it's coming up and also just like
with parameters can also set up the
return type as an object out of does
that look like well same deal I just say
colon then I provide the curries and
what are we returning from this function
I'm going to go with ID which again is
going to be a number and also there's
going to be is active in this object and
that one will be a Boolean and again we
set up the
Cur so we have two sets of curries over
here and we also have two sets over here
because we have one for return and one
for
functionality and as far as the logic I
just want to return an object from this
function and I need to make sure I
follow this pattern correct I need to
make sure that I return a number and a
Boolean so in this case I'll just right
away grab whatever I have over here and
also as far as the is active I'm just
going to do some basic logic I'm going
to say ID and then I'm going to use the
modulus operator essentially if ID
modulus 2 is equal to zero then it's
going to be true which means essentially
that it's an even number if not then
it's going to be false so now let's try
it out we're going to go with const
first set it equal to create employee
and then let's pass in our object so in
this case it's going to be one then copy
and paste this will be equal to a second
over here and then we want to log both
of these results so let's look for first
and second let me navigate to a console
and for some
reason says false because yep I didn't
change this one this should be equal to
two so now the first one is active is
false and then the second one is active
is true again we really don't care about
the functionality I mean we can
definitely hardcode over here doesn't
really matter so hopefully it's clear if
we have an object we nicely set up right
away The annotation at least with the
current knowledge we have now also we
have alternative approach where we can
give some kind of name to this object
and then we can just use it inside of
the function body again please keep in
mind the general idea as far as
typescript doesn't change but I do want
to make sure that we understand that we
have multiple approaches so let me call
this
alternative over here then we will go
with function create student in this
case and I know that I'm going to get
the
object and I'm just going to give it a
name of student so this still will be
object but I'll just access it with
student. student do and same deal I want
to go with my annotation I'll say that
ID will be number and name will be equal
to a string over here and and then as
far as D function body I'm actually
going to go with void so we're not going
to return anything from this function
and we're just going to log stuff so let
me scroll down a little bit let's set up
the template literal welcome to the
course I
guess and let's access the student where
we go with student and notice we right
away get the suggestion which properties
are on this object since this is what we
specified
in our type annotation and in this case
I want to go with name and then to
uppercase also please keep in mind that
yes we can the structure right here in a
function body as well that's totally an
option so now let me call
it with the new student so in this case
just to again showcase that we have
multiple approaches we want to go with
student we want to set it equal to an
object I'm going to go with five over
here and name is going to be Anna and
I'm just going to rely on typescript to
infer the type and then we'll go with
create student pass in the new student
and if everything is correct we should
have the value in the console and with
this in place we can move on to the next
topic okay and before we move on and
start working on our next challenge
let's also cover the access property
check gotcha and for this one actually
we don't need to create too much code
from the scratch I'm just going to
remove my first function from the
previous video I'll leave create student
as it is and I simply want to invoke it
right
below and in this case I will pass
everything in line so unlike previously
where we set the object now I'll provide
all of these properties one by one let's
start over here with ID I'll set it
equal to one as note it's totally
irrelevant to what we pass in here
that's not the gotcha the gotcha is
following if we add here extra property
what do you think is going to happen
well we have a type annotation for ID in
string correct so I mean logic tells us
that if we add here email and we set it
equal to Bobo at gmail.com typescript is
going to complain and you're totally
correct essentially it says Hey listen
you didn't specify that there's going to
be an email while you're adding this to
the object so this is something we
expect however notice this interesting
Behavior where I can go here with an
and essentially pass in some kind of
value and you know what it's going to
work typescript is not going to complain
so yeah this is this interesting
Behavior
where when we pass in object properties
in line typescript expects to match this
exactly so if we'll add some extra
properties TPT will immediately complain
because in typescript mind we have a
full control of what we're adding in
line however if we're just referencing
the object and there's an extra property
the only thing typescript cares about
are the properties that are in the type
notation so if there's 120 extra
properties typescript is like okay do
you have an ID and name if yes we're
good to go if not then of course there's
still going to be an issue hopefully
it's clear just remember this gotcha and
you'll be good to go all right I think
we're ready for our next challenge and
at least in my opinion this one is going
to be super interesting because we'll
combine multiple things from the
previous videos so we want to create a
process data function which is going to
accept two parameters first one is going
to be input parameter which can be a
string or a number and second one will
be a config object and instead of that
config object we'll have the reverse
property which is a Boolean so if we
pass in a number we just want to
multiply the number with its own value
essentially input multiplied by the
input however if the input is the string
our second option and if the reverse is
true we want to reverse the string
and set it uppercase now if we provide a
string but the reverse is set to false
well in that case we'll simply set up
the string to be uppercase and just
return it so let me navigate to my
tutorial I think I'll just remove all of
this logic and you know what for stars I
want to set up a
function in here I'm going to call the
this
process data I'm not going to set up any
parameters yet same goes for
functionality and I simply want to log
it in three places essentially invoke it
and then log it so in the first case I'm
going to pass in 10 and
then I'll set up two more hellos so
these are going to be instances where we
pass in the string and now as far as the
process data like I said we have input
over here but we want to use the type
Union so either it's going to be a
string or it will be a number so that
will be our first parameter now the
second one is the config one if we pass
this config in there there's going to be
a reverse property and as a sign note I
actually forgot to do that so first one
is hello and then we want to go with our
config
object and I will set the reverse equals
to true so let's navigate to our
parameters and let's set up the second
one so I'm going to call this config
it's an object and in there I'll have
the reverse property so I'll set it
equal to a Boolean now here's the kicker
what if I pass in the number do I really
care about that reverse one
and the answer is no I only care about
it if it's a string correct only then
we'll check but if it's a number I mean
doesn't really matter and therefore I
can nicely set this as default reverse
false so I'm not going to have to do
that additional check basically Once I
pass in the number I don't have to pass
this additional config object so in here
let's go with default one and set it
equal to verse and false now let's also
set up what we're returning from this
function so either it's going to be a
string or a number and now when it comes
to logic well we have two options
correct so we can have a string or a
number so we do need to set up a typ
guard if we want to multiply it I want
to make sure that it's actually a number
so let's go with if then type off if the
input is equal to a number well that's
when we want to multiply and return so
let's go with return that input times
input and it looks like I have a tiny
typ over here this should be return and
also we want to set up the else and in
here we're going to go with the return
then we'll check the config reverse so
by default it's going to be false so if
it's true then we want to set it to
uppercase split reverse and join if not
well then we'll simply return it with
the uppercase so let's set up over here
a dinary operator we're going to go with
input then to uppercase let's invoke
that then we're going to split it then
we'll call a reverse on
it over here and then lastly let's use
join method let's do this and if it's
false which is the default one we're
going to go with input then
two uppercase and we're going to invoke
it so now let me navigate to the browser
and let's see so I have 100 then I have
straight up hello just to uppercase and
then I have the reverse value again in
my opinion the biggest gotcha is over
here you see if you're not going to
provide this default value over here
then pretty much every time you'll
invoke this processed
data it's also expecting this object
over here and if that's the
functionality you want to go for it's
definitely an option but in my opinion
it's super useful to add this default
one because in that case well if it's a
number or if I don't want to actually
reverse it well I simply don't provide
that argument at least that was my line
magic and with this in place we're done
with the challenge and we can move on to
the next topic all right and we have
finally arrived at the type alas at
least in my opinion one of the most
exciting topics because once I learned
the topic I was super super excited
since it just eliminated bunch of clunky
code and for this one actually want to
start with the code
already present because I want to cover
some stuff on I highly encourage you to
do pretty much the same there's really
no need to type this from the scratch so
grab it from the readme and then let's
go line by line so we have two objects
and we nicely set up over here the type
annotations where ID is a number name is
a string and is active is a buan so if
I'm setting up some wrong values
typescript is going to be super helpful
and then we have a function which again
is looking for a user and that user must
have this particular shape ID is a
number name is a string and is active is
a buing okay beautiful and not only that
but from this function for some weird
reason we return the same thing we
return the same shape we return ID name
and is active and so is the
functionality we just set it to
uppercase and then return the user and I
can tell you right away that there's
nothing wrong with this code as far as
functionality all of this works what is
the biggest issue I mean we have code
over here same code over here same code
over here and then we have the return
and this is just one file what do we
have like 20 lines of code and pretty
much we just
constantly keep repeating this so
without further Ado I want to introduce
you to a type areas in typescript which
again in my opinion is extremely helpful
feature now before we continue let me
just make sure that we are all on the
same page you see a type Alias is just a
new name or a shorthand for existing
type and in this case we're talking
about this type over here this type
annotation so nothing is actually going
to change as far as this syntax is
concerned however with type Alias it's
going to be easier to reuse this one so
again please keep in mind we're not
creating a new type it's just an Alas
and all of the same rules apply to the
alas one that's why I
wanted initially to cover how we set up
such inline type annotation because
nothing is going to change as far as our
functionality including the optional
property and read only modifier the only
difference well now the code is going to
be in one place so if we ever want to
change something we will only need to do
that in one specific place and also our
code is going to be less clunky because
we'll just use that name and once I'm
done with my long and B Bing monologue
why don't we set it up and essentially
the syntax is following we want to go
with type that's the keyword now the
convention is to go with the uppercase
but you don't have to I mean you can
call this also like this but in my case
I will go with user and like I said
before the syntax is the same so I
simply want to take my first instance
and set it equal to my user so now all
throughout
my file document project whatever I can
use this user and this will mean the
same exact thing so in here I can go
with yeah John is going to be object and
a type is actually going to be user same
is going to be over here Susan is going
to be a user now when we're creating a
user what is the type well it's a user
type and you can probably already guess
same is going to be over here so we can
go with user and now me question which
one is easier to manage and
read and if you said the second one
you're absolutely correct so I can mess
with you and say that you know what no
actually this one was easier to work
with but in reality we can clearly see
that this is definitely easier to work
with and I'm skipping a little bit ahead
but we can actually also export this one
as well as well so it's definitely an
option so let's say we set it up in one
file and then if we ever want to use
this type alas somewhere else we can
nicely export it import it in the file
and we're pretty much good to go okay um
before we move on and start working on
our next challenge I also want to
quickly showcase that we're not limited
to using type Alias for object so it's
definitely an option it's definitely
something thing we're going to do but
you can also do it for our previous
examples as well for example I can go
here with type I'm going to call this
string or number and I'll set it equal
to string then use the union type and
set it equal to a number so now anywhere
in my project where I want to use the
union string or number I can use my type
Alias instead of this hardcoded value so
let's say that there's a value this one
will have a type string or number and
then we can go with value hello and also
we can set the value equal to 1 two 3
now is this something you're going to
see
often uh most likely not but still I
definitely want to make sure that you
know that it is a possibility now
something that you will see quite often
at least in my code is this I'm going to
set up an alas but in this case I'm
doing that for the literal type so I'm
going to go with light or dark so this
will be my tee and those are the values
so it can be only light or dark and now
if I have a theme
variable I can go type theme then let me
just change the values here notice how I
right away have only these two options
something I have discussed already quite
a few times
and in this case I'm going to go with
light and what's also super super
awesome that I can use the same theme
one in the function so if I go here with
set
theme it's going to be looking for a
parameter by the name of T and the type
over here is actually going to be a
theme and now I want to set my theme
variable equal to
whatever parameter gets passed in so now
when we invoke the theme same deal over
here notice how we can only use these
two values again super super helpful
especially as your project grows bigger
so we can nicely set up this Alias and
then use it when we set up the property
or when we pass some parameter in the
function and up next let's work on
another challenge and and during the
challenge we'll cover a few interesting
things we'll cover how we can set up
type Alias with the array how we can set
up type alas with type Union and how to
set up a typ guard if we're working with
the object so here's the challenge we
want to set up two types one is going to
be the employee type and second one will
be a manager type now for employee
will'll set up two instances and then I
guess manager will set up only one now
the key difference is that for a manager
there's going to be employees property
and it's actually going to be an array
of employee types so this is where we'll
combine the Alias with the array and
then we want to set up a function which
actually is going to accept both types
whether that is the employee or the
manager
and if the instance is the manager then
we just want to showcase how many
employees they have and if it's not the
case then we'll just log in which
department the employee is working so
let's try to set this one
up I'm going to go with my alas first
and I'm looking for
employee so this one will set it equal
to an object there's going to be an ID
property which is a number then we'll go
with name we'll set that one equal to a
string and then also there's going to be
a department and for some
reason I have a hinch that this is not
correct typing so let me fix that so
we're looking over here for Department
which is a string
now there's also going to be an alias
for
manager for this one same deal ID number
name String so let me just copy them in
order to make it faster and now I want
to set up the
employees which is going to be an array
but an array of what it's not going to
be an array of strings or numbers and if
you remember in one of the previous
examples we actually covered that we can
set up type to be an object only in this
case we already have the type Alias for
that so I can simply say yeah it's going
to be an array but it's going to be an
array of employees okay good now let's
set up those instances and then we'll
work on a function so for starters
there's going to be first employee we'll
right away set up the type just so we
don't mess up anything
ed1 then
name let's set it up and also let's come
up with the department and in my case
I'm going to go with sales let me copy
and paste now I want to change the
variable name so in here we'll set up as
Steve same deal over here and then as
far as the department let's go with HR
then let's set up our manager as well so
this will be Bob the type will be
manager ID one name Bob or Bobo even
better and then we'll go with employees
and this is our array correct so now I
want to grab Alice and deep so let's set
these two up and now let's invoke the
function the print staff details but of
course before I can invoke
it it would be useful if we would have
this function in the first place correct
so let me come up with the function I'm
going to call this print staff and then
details but here's the kicker how are we
going to pass this in because at the
moment we have two
types so are we going to pass in just
employee and then set up another
function for the manager or we can
somehow some way combine the two and the
answer is well we can use the type Union
so essentially I can go with type and
then staff and set it equal to employee
or it's going to be a manager and now
this is our type so now I can nicely go
to print staff detail details and say
okay there's going to be an object and
as far as the type actually going to be
equal to a stat now I do want to set up
the void over here since we're not going
to return anything and now another
million doll question well how we can
check whether the staff object is the
employee or a
manager because if it's a manager then
we do have an array but if it's the
employee that's not the case and we
cannot go with well is type off equal to
an object well both of them are equal to
an object so that's not going to make
much difference here's what we want to
do so we want to go with our condition
and then we need to pick a property
which is specific to the object so in
this case that's the employees correct
so we go here with the property and we
say in and then our object over here so
that's the staff if it's the case well
then we know that it's a manager if not
then we know it's a staff one so let's
go and log something here we're going to
go with staff name so let me access this
one
staff name and then we'll say is an
employee in the specific department so
in here we want to access again the
staff one and now we're looking for
Department again a property which is not
on a manager and again typescript is
smart it knows that if there's an
employees this is going to be a manager
if not well that's the staff then and I
can access the department so let me add
this one and now I want to just grab
this console log and we'll just change a
few things around still going to be a
console log but we're going to go with
manager and notice how right away
typescript is correcting us essentially
it says well department does not exist
on type manager so now what do we want
to do well we'll remove this we're going
to go with employees and we're looking
for length and let's just type
employees okay good let's try it out
going to navigate to the bottom and
we're going to go with print staff
details let's pass in the first one and
and let's also pass in the Bob once we
navigate to the browser we see that
Alice is the employee and Bob is the
manager so this is how we can combine
multiple features this is how we can set
up type Alias with the type Union this
is how we can start using type aliases
with the array and this is how we can
set up a typ guard if we are working
with the object uh next let's discuss
the intersection type in Union which is
a way for us to combine multiple types
into one let's imagine this scenario we
have a type book it is equal to a number
name is equal to a string and there's
also a price so we set up this number
over here and we're good to go then
let's create let's say two instances I'm
going to call this book one is equal to
an object and let's right away set up
our type our book type and then in here
let's provide some dummy values ID will
be equal to one name will be how to cook
a dragon because why not and also let's
set up some kind of price so in this
case it's going to be some random
15 then let me copy and
paste and instead of Po one this is
going to be b 2 now the type will stay
the same the ID will be two as far as
the name we're going to go with the
secret life of unicorns and we're going
to set the price equal to
18 so all this is good but what if I
have a discounted book where not only I
have these three properties but there's
also a discount so first let's set it up
and you know what I think we can speed
this up a little bit where it's not
going to be a book we're going to go
with
discounted book okay good now for now
type will be book but clearly we'll have
some issues I can right away tell you
that then let's come up with the name in
my case I'm going to go with this one
price will be equal to 25 and we also
want to add this discount property and
we'll set this one equal to
0.15 and notice the moment we do that
typescript complains why well because
it's not in our types so there is no
discon anywhere here so what's the
solution well we could create another
type correct we could just copy and
paste and set up over here a discounted
book type and then just add that
discount property it's definitely an
option or we can nicely utilize the
intersection type how's that going to
look like well we have multiple ways how
we can set this up you can definitely do
it over here in line where you go with
and operator and you just add what more
types you want to have for this
particular instance so in this case I
can go with discount and I can set it
equal to a number and notice typescript
doesn't complain anymore so now
essentially it uses all of the
properties from the book type already
but we just added nicely the discount as
well so that's one option or we can set
up another alas now the logic here is
not going to change so I can just cut it
out and go type then discounted book and
we're going to set it equal to this one
so now for my discounted book I can use
the discounted book type Alas and again
the difference with Union type it's
either going to be this type or the type
on the other side of the pipe however
with the intersection type now we
combine them now we say yeah it's going
to have all of the properties that we
have in the book type and also there's
going to be this discount one which is a
type number all right and at the end of
the type Alias section I quickly want to
mention that type Alias also supports
computed properties so we we don't
always have to hardore code for example
if I have a tiger object and eventually
I'll set up the type you know what for
now let's just set up the object in here
I can go with age and set it equal to
five so nothing new but we can also set
up a variable in there we'll have a
string and we'll actually use that
string as a property name so straight up
JavaScript let's say we're going to go
with const prop name and we're going to
set it equal to age and now instead of
hard coding I can just go with prop name
so if I'm going to change the string
value now my property is also going to
change over here in a tiger and we can
do the same thing in type Alias I can go
with type
animal let's set it equal to our object
and then instead of hard coding we're
going to go with prop name and set it
equal to a number I just need to follow
the proper syntax over here and now
let's set up the type for a tiger and
we're good to go so just like in regular
JavaScript we can use computed
properties in type alas okay and up next
let's cover interface type which is used
to describe the shape of an object as a
side note we are purposely covering
interface type right after type Alias
simply because they are very similar and
yes before you ask quite often you can
use either one of them and the result is
going to be the same now what do
programmers do when the same thing can
be achieved in multiple ways well we
argue about it on Twitter and try to
convince everyone else that our solution
is somehow some way
better why because apparently that's the
best use of our time and remember if all
the other arguments don't work you can
always say it's just a better practice
to do it apparently that one always
works jokes aside I do personally prefer
type Alias over interface and therefore
during the course most likely you'll see
type Alias syntax more often but just
like I mentioned before it really comes
down to your preference despite what yet
another Twitter Guru says okay hopefully
I did not scare you away with my joke SL
rant and if you're still here let's set
up a book object so I'm going to
navigate to my
tutorial I'm going to call this deep
work and you'll see a second why so
we're going to go here with deep work if
I only would know how to spell this is
going to be my object we're going to go
over here with this
ISBN which essentially is just used for
books as the ID so in my case I'm just
going to go with one two three then
we're going to come up with title I'm
going to call this deep work as a sign
of this is an awesome book again I'm by
any means not being sponsored or I'm not
trying to sell you this book but this is
an awesome book uh you won't regret
whatever dollar it costs so we're going
to go over here with author that is
going to be Cal
Newport awesome and then let's also set
up the genre and I believe it's
selfhelp self and we're looking for help
now I do need to add over here a comma
and we already know how to set up ttype
alas so probably this is something we're
going to set up at the very end but we
also can use the interface again this is
something that we use if we want to
describe the shape of the object now the
keyword is interface then we come up
with a name same deal lowercase
uppercase totally up to you in my case
I'm going to go with the uppercase and
then instead of the equal sign we just
want to set up over here the curlies and
then same deal we go with the property
name and then the type and I write away
want to mention that the
readon modifier which we covered with
type alas as well as the optional
property is also allowed and therefore
I'll go right away with read only then
I'll Target basically this book ID and
I'll set it equal to a number remember
if we'll try to modify this value later
it's not going to work then also let's
set up a string okay beautiful that's
going to be 40 title then the same deal
we're going to do with author we're
going to set it equal to a string and
the same is going to be for genre but
I'm going to set it as optional again
just so we get this one out of the way I
don't think we need to spend a separate
video on these two things since we have
covered them before and effectively if I
go here where is my deep work and if I
set it equal to my book I'm going to go
so if for some reason I go with a deep
work and try to modify this property
which is read only let's say I'm going
to go with some value notice typescript
is going to complain same deal is going
to be if I'll try to add property that
doesn't exist let's say price and I'm
going to set it equal to
800 that is not going to work and then
let's say for genre since it's optional
property I can just remove it basically
comment out and my code is still going
to work and if you enjoy working on the
challenges you can set up a type Alias
for this deep work object and you'll see
that in this scenario you can use either
of those approaches and the result is
going to be exactly the same okay and up
next let's discuss methods in
interfaces and we're going to spend few
video videos on it just because it's not
in my opinion a complex topic but it can
be a little bit confusing because you
can set up methods as properties as well
so essentially you can mix and match and
at that point it might look a little
confusing so start with just straight up
approach which is my preference and then
I'll show you the alternative code that
you might see somewhere in the wild so
effectively if this book has for example
a method of print author I just go
directly to my interface in this case
I'm going to add a comment and I'm going
to come up with that method now please
keep in mind here we're not typing any
logic I'm just saying yes there's going
to be a print method or you know what
should be print author for some reason I
went with print method
it's not going to look for any
parameters and then as far as the return
it's not going to return anything it's
just going to log so the moment I do
that now notice I have typescript
complaining because I haven't set up
that method over here you know what just
so I have
less code I'm just going to remove those
comments over here so now let's set up
that method again this is going to be my
Approach where I go print auth
setup over here my method and in this
case I'm not looking for any prams we'll
cover that in a second and then we just
go with log and then since I'm not using
the arrow function syntax I can access
any of these properties over here by
using this again we're going to cover
the arrow syntax approach a little later
for now we just want to log the author
that's it so now let's go go right after
the object we're going to go deep work
then we're going to invoke print author
and if everything is correct we should
see in a console the author so let me
take a look at the browser and yep I
have my Cal Newport so my logic works
now what is the syntax if there's going
to be a parameter well let's try it out
in this case I'm going to go with print
title and I'm just going add some
message after the title I'll say this
book is awesome or something along those
lines so let's go here with
title we set up the parameter as a sign
note this name doesn't need to match
whatever we set up over here in the
instance so in here I'm just saying yes
there's going to be some kind of
parameter and I'm going to reference
this as message now type is going to to
be string and Just for kicks let's also
return from this function again we're
not setting up any kind of logic over
here I'm just saying that there's going
to be a method by the name of print
title so now we want to scroll down and
same deal we want to set up our function
so I'm going to go with print title and
I'm just going to call this value just
to Showcase again they don't need to
match now is my preference to set them
up the same yes but again that is just
my preference and then inside of the
function same deal in this case I do
want to return and notice how typescript
essentially is complaining that hey you
said that it's going to be a string over
here and at the moment it's still void
what's up with that so let me just
access again this dot since we're not
using the arrow function then we can
access nicely title and I'm going to
provide over here whatever message is
going to be passed in and then let's
keep on moving I guess right after the
author either we can log it right away
or in my case I think I'm just going to
store it in a result so let's go deep
work then print uh nope it's not the one
we want to go with print title and then
let's say
is awesome book so this will return a
string so what do we do with string
value well we log it and yes it looks
like everything is correct but text is
not so let me set it up properly or here
again if we have a method in here we
just set up the
blueprint so what is going to be the
method name whether we're going to
accept any parameters if we do then it's
useful to set up right away a type and
also whether we're going to return
something from this function or or no
and then inside of the instance we set
up the method and we just need to follow
our blueprint so if we're not returning
anything from this
function we just set up the
functionality if we are returning we
need to make sure that the types match
and with this syntax we can access any
Properties by using this keyword okay
and up next let's cover an alternative
way how we can set up method me in
interfaces now let me stress something
technically this video is optional I
just wanted to cover this because you
might encounter such syntax somewhere in
the wild but I personally tend to stick
with the approach we covered in the
previous video simply because I find it
way more
straightforward alternatively we can set
up the method in the interface as a
property how's that going to look look
like well we can go here with print
something and again the example is going
to be pretty straightforward and
essentially we set it here equal to a
function but please keep in mind this is
a syntax we're not setting up over here
the arrow function this is just the
syntax that we're using so we say that
it's going to return a number and then
we set it equal to some value and pass
in the number and now with this proper
in place we want to go to a deep work
object and here we have quite a few
options to set up this function so I'm
going to add these comments I'm going to
say First Option then there's going to
be a second option and I believe there's
going to be a third one as well but
we'll see most likely I will improvise
as we go so first option well we can use
the good old
function keyword so I'm going to go with
print something that's going to be my
property right now then I go with
function same deal it's looking for some
value now what is going to be the value
that will be a number correct and then
as far as the function body just so I
return a number essentially I'm just
going to go with some value now let me
scroll down a little bit I mean most
likely we can just remove these values
just so our console is less busy and I
can go with my deep work then let's go
with print
something we want to pass in some number
why not
34 and then let me set up the log and
let me move this sucker inside then let
me remove my semicolon let's navigate
here and notice I have 34 so again
instead of setting up the straight up
method now I set up the proper
which is equal to a
function in here if I have some
parameters then I set up the type and I
also say well what is this function
returning again you don't have to return
something from this function just
because it's a property right now so
that is going to be our first option
okay let's common this one out and our
second option is going to be Arrow
function so we can go here with print
something
remember we want to access the some
value that is going to be our parameter
and then as far as the logic I'm going
to go with some value now there's a
reason why I'm setting up the curlies
I'm fully aware that we can set up the
implicit return the reason for that is
because I wanted to Showcase
that there's a gacha with this and arrow
functions so Arrow function is going to
capture the global this please keep that
in mind if you're using Arrow function
functions unlike the good old regular
function where we right away have access
to this which is scoped to this instance
it's not going to be the case with the
arrow function so for example if you
want to access any of the properties in
my case I'm going to go with author
we'll have to go with deep work and then
the author now let's navigate over here
notice we have both we have the 34 and
we also have the author so this will be
our second option and I guess what was
somewhat
confusing is the fact that you can also
do another
way where I can go with print something
and effectively just use the syntax we
already used before so this also is
going to work and that's why again my
preference is just to use this approach
where I set up the method and I clearly
do the same thing inside of my instance
so this will also work so we can go here
with return and then some value print
something and notice once we navigate
back to the console this also works and
lastly I'm not trying to confuse you too
much but this also is going to work so
notice we have over here this print
author which is set up as a method but
we can set this one up as a property so
we can go here with print author now I
believe typescript is going to complain
so I'll uncomment the first one my
Approach I guess if I have a property
then we're going to go print
author and we will set this up as a
property and we'll set it equal to an
arrow function again not trying to
confuse you too much but just showing
you alternative syntax that you might
see somewhere again
remember we don't want to use this we
actually want to go with deep work and
then we're going to look for author now
tespt will complain since I already
have my first approach but again if you
navigate to the console you'll see that
the result is there now I'm not calling
print author that's the reason why I
don't have it let me go here let me
invoke it and you'll see that as far as
functionality it works again what's
confusing is that you can set the
property equal to a function so instead
of straight up method you set up a
property which is actually equal to a
function and then you can start doing
this mix and match where yeah it was a
property but then actually in here it's
going to be a method and then the other
way that's why my preference is to set
up methods with this syntax and and the
same in my instance just set up straight
up methods simply because in my opinion
it's just less confusing hopefully I
didn't lose too many of you and with
this in place now we can start working
on our next task okay and once we're
familiar with the interface fundamentals
let's work on a small challenge where we
want to set up a computer interface
inside of it we want to set up few
properties one is going to be read only
which is going to be for object then
brand equals to string Ram is going to
be number upgrade ram will be a
method and in there we're going to be
looking for number and we'll return a
number and also there's going to be a
storage property which is going to be
optional but the type is going to be
number also once we have the
interface we will set up the instance
and we'll provide the properties apart
from the optional one and then finally
we'll also invoke the upgrade ram method
so let's try it out let me set up my
interface name will be a
computer let's go line by line this one
will be read only so I'll set it equal
to my ID then brand equals to A String
after that let's go with the ram that
will be number okay then upgrade
ram this one will be a
method so we'll look for
increase and this actually is going to
be a number now from this function we
want to return a number and then also
let's set up the storage which will be
optional and we'll set it equal to a
number so now let's create our instance
in my case it's going to be a
laptop so set it equal to our object and
we right away want to set up our
interface type now let's pass in those
values there will be an
ID then a brand is going to be a random
brand after that we have a ram we'll set
it equal to 8 I guess 8 gigs and let's
also set up our method upgrade ram as
far as the parameter I'm going to go
with different name just so you can see
that for sure everything works even
though the names don't match and in here
let's just set up functionality where we
grab the current Ram value and we just
add the amount which is past in and then
since I want to return a number I'm just
going to go with this Dot and RAM this
is what we're
returning since the storage is optional
I'm not going to pass it in let's just
set up our instance then storage and now
I'm going to set it equal to
256 we can log it so let's go over here
with our laptop let's see yep I have my
object a brand RAM and everything up to
the upgrade RAM and also let's invoke
the upgrade ram let's pass in some value
and let's keep our console locked so
we're going to go over here with another
one I guess since we're returning the
value so let's go with laptop upgrade
ram let's pass in some kind of value in
my case I'm going to go with four and
then if everything is correct this is
what we're getting back from the method
and also our Ram instead of eight is
actually equal to 12 okay and up next
let's see how we can perform interface
merging how we can extend the interface
and then we'll work on another challenge
and during that challenge we'll see how
we can use typu with interface for
starters I want to create two interfaces
one for person and one for dog owner now
both of them will have two properties I
guess well one is going to be be a
method name and let's say details so
let's go with
interface I'm going to go with person
I'm looking for name I'll set it equal
to a string and also there's going to be
a get details method which will return a
string so that's my person one and I
also want to set up one for dog owner so
let's just go here dog
owner so that one will have a dog name I
guess that's going to be my property
name which is going to be string and
then instead of get details we're going
to go get
dog details let's invoke it and again
we're looking for a string over here
okay beautiful and first let's see how
we can merge the interfaces so once I
have my person one I want to create my
object I'm going to call this person and
the type is going to be equal to my
person interface now what are the two
values we need to provide first we need
to go with John and as I not I'm missing
here the equal sign and the second will
be the get details one so let's just go
with get
details that's the
function and we're going
to set up the
functionality with the template string
name
colon then let me access the this dot so
this do name and also let's add
age so this one will also be equal to
this Dot and then the
age now notice over here how we don't
have the age correct and one way is to
go back and set it up over here in this
person but there's another way how we
can add this property and that is by
merging the
interfaces and I know that this looks a
little funky in the beginning please
keep in mind that most likely you're not
going to do that in the same file but
let's say if you're getting the
interface from somewhere if you know the
name you can do something like this and
as a said note yes essentially I'm using
the same name I go with interface person
and then I just go with age now number
so I add that extra property over here
now this also needs to be in my instance
correct so in here I need to come up
with some kind of value and now the get
details is correct I can access both the
name and age so I have the first one and
then I just merge so whatever properties
I'm going to set it up over here yes
essentially if I create this instance
now all of these properties
will have to be there hopefully that is
clear now just a showcase let me go with
person Dot and then get details let's
invoke it and for some reason I don't
see anything in the console and of
course because I'm returning so what am
I doing here let me go with my log me
move this sucker
up and now let's try it out yep I have
name John and age is 30
and up next let's see how we can extend
the interface which is a way for us to
create a new
interface that inherits or essentially
just uses the properties and
methods from the existing interface now
it sounds more complex than it actually
is imagine the scenario we have an
employee
instance and for now we're not going to
set the type let's just set it equal to
an object I'm going to go with some kind
of name I'm going to go not with John
let's go with Jane over here then let's
also set up the age CU
remember we already added this to a
person so now essentially we need name
we need get details and we also need an
age so let's set up some kind of age
here then let's go with our details
however in this case since we're going
to add one more
property the return is going to be a
little bit different here's the thing
Jane is a person that kind of makes
sense correct so I can definitely set it
equal to a person and call it a day
however let's imagine that Jane since
she's an employee she also has the
employee ID now I don't want to add it
to a person so I want to keep this as a
separate interface but I do want to use
all of the properties that I already
have in my person one and just add on
that employee ID so here's how we can do
that we go with
interface then come up with a name in my
case I'm going to go with employee and
then we go with this extends and now
we're just looking for a specific
interface we want to use and now let's
just add this
employee ID and set it equal to a number
so now Jane not only she's going to be a
person but she's also going to be an
employee so now when we set up the type
we go with employee and now not only I
have name and age but I also need to
apply this employee ID so let's add this
one let's say over here 1 two 3 and then
remember details needs to return a
string so in this case I'm just going to
grab whatever we have over here and then
let's just add the employee ID as well
so let's add a
comma we're going to go with ID and then
let's access this Dot and then employee
ID now just so we can see that
everything works I guess instead of
person
details let me go with
employee get details and yep and have
all three values in the console now we
can also inherit from multiple
interfaces essentially I can extend from
the person as well as the dog
owner so we're going to go with a
manager instance I guess so we're going
to go here with
manager eventually we'll set up the type
for now I just want to provide a name
it's going to be equal to a bob and also
for now let's go with the AG which will
be equal to
A35 now when it comes to
Bob not only is going to be a person so
we'll need to provide all of the
properties but also let's imagine that
he's a dog owner so essentially we want
to extend from both interfaces that we
already currently have the person and a
dog owner now since Bob is a manager I
also want to add a a method onto the
interface and in my case I'm going to
call this manage people so let's move
where we have Bob and first I guess
let's construct the interface and then
we'll worry about the properties so
we're going to go with interface manager
for stars let's just add that method
that I was talking about so I simply
want to go with manage
people uh it's not going to take any
parameters and we're not going to return
anything and if we set this equal to a
bob we'll have an issue since we have
two properties that we haven't set up in
our interface so now let's go with
extends and one by one let's look for
those interfaces so we're looking for a
person and a dog owner so Bob is a
manager a person and a dog owner and now
if I navigate over here and set it equal
to manager type I will have to provide
all of these values what they are well
we need to provide a dog name let's go
direct Rex it's a super popular name
then we also have get details and you
know what in this case I will speed this
up I really don't want to type
everything from the scratch so we have
get details what do we want to access
here I guess let's just go with age
since we don't have the employee ID then
we also have one for dog so let's go
with get dog
details now we will go with name is and
then let's access the dog
name dog name over here then let's
remove the age guess we don't need it
and lastly let's set up that manage
people manage people let's invoke it and
for now we simply want to log so let's
set up a console log and let's write a
text managing people and lastly just to
test it out that everything works want
to go with manager and it's invoke
manage people if everything is correct
we should have this text in a console
and again this is how we can merge
interfaces by essentially using the same
name and just adding the properties
another name that you might hear is
reopen essentially they mean the same
thing where we declare the interface
with the same name one more time and
then typescript is going to merge them
together and we can also extend so let's
say if we have an interface with some
properties and methods and we just want
to grab methods and properties from some
other interface simply go with extends
we look for that specific interface and
in the process we'll right away get
those methods
and properties and with this in place we
can move on to the next task and up next
let's work on another
challenge and during the challenge we'll
see how we can use
typu with
the interface now I did split up the
challenge into multiple videos so in the
first video we'll kind of prepare
everything we'll set up our function we
will will return one of the interface
types and then in the following video we
will work on more logic where we'll see
how we can use the typ guard so I didn't
want to jam everything in one video
because there's quite a few lines of
code
and I mean the most important thing is
kind of at the very end and usually if
it's a long video then people just lose
the interest so long story short we want
to define a person interface with the
name String then we want to set up a dog
owner which extends the person and just
add the dog name which is going to be a
string and also we want to set up a
manager which extends the person so not
person and dog owner no the manager is
going to extend only the person and
we'll just add two more methods on it
then we want to set up the instance
which can be either of them so we'll use
the Union type and actually we'll set it
equal to get employee function now in
there in get employee we'll just call
math.random and based on value we'll
return one of those interfaces so
whether a person dog owner and a manager
and again in the next video we'll see
how we can use the typ guard because
there's a
gacha that we need to be aware of STS
let's navigate to tutorial one by one
let's set it up so this is an interface
we want to go with person let's go with
name equals string okay then let's also
set up a dog
owner so we have here
interface dog owner now that one will
extend the person so we'll get that name
property and we also want to add the dog
name dog name will be equal to a string
and then the last interface is going to
be a
manager which is going to extend the
person and in here let's go with manage
people that's our method and we're
simply going to go with void and also
copy and paste and let's say delegate
tasks so those are our two
functions and then let's set up our our
instance but before we do that let's
also set up a function and I'm going to
call this get
employe and this is the function that
we're going to use in our employee
instance so for starters I'm going to go
here with const
employee and as far as the type I'm
going to use the union type so either
it's going to be a person or it's going
to be a dog owner or it's going to be a
manager and I'm going to say it equal to
my get employee and I'm going to invoke
it now I didn't want to move this
function up simply because in the
following video we'll write the code
over here and I think it's going to be
less confusing so let me move it up
that's going to be our function and
here's the task inside of the get
employee I want to
invoke math. random and then based on
the value if it's say less than
0.33 well then I'm just going to return
a person interface if not then it's
going to be a dog owner and if not then
it's going to be a manager so I have
this employee notice over here it just
says well the moment you're returning
void
and that's not what the employee is
expecting so in here I'm looking for one
of these three
values now in this get employee we're
not not going to pass any
parameters simply want to go with our
logic so let's set up the random that
one will be equal to math. random so
we'll get some random value between zero
and one and now let's just work on those
returns but also let's set up the type
right away so we're looking for
person we'll also grab the dog owner and
potentially this could be a manager so
again we don't know what the value is
going to be so every time we'll refresh
the browser we'll get some random value
over here and then based on that value
we'll set up that return so let's start
with our first option if the value is
less than
0.33 well in that case I want to go here
and I want to return a name John so
which interface is that well that's the
person one correct so these two match
then let's also set up another else
if so if the random is less than
0.66 in that case let me grab this and
now we just want to add the dog name so
in this case we're going to go with
Sarah and we're going to go with dog
name and we're going to set it equal to
Rex now
lastly if it's not less than 0.33 if
it's not less than
0.66 then we're going to go with another
else and in here we want to return a
manager interface so in this case we're
going to go with return Then object name
will be equal to a bob and then let's
set up those two methods we're going to
go with manage people and as far as the
logic let me just go with console log
and we're going to say managing
people dot okay good and then let's do
the same thing for delegate
tasks that's my function and as far as
the text it's going to
match now let me navigate where I have
the employee and let's just log it like
I said we'll have to refresh the browser
so once I navigate over here notice this
was my person instance then I get over
here the manager correct then I get the
dog owner and as you can see every time
we refresh the browser we're getting a
different value so in here
again we want to set get employee and we
want to make sure that we only return
one of these interfaces we use the unit
type and then when it comes to the
instance same deal I'm looking for one
of these three values so employee is
going to be either a person a dog owner
or a manager and in the following video
we'll introduce the typ guard and make
this challenge more complex okay and
with this in place now let's make this
challenge more complex by adding a
function which is going to check for
specific interface and only if it's a
manager we want to invoke delegate tasks
because here's the kicker we get back
our object we store it in the employee
and if we try to go with name everything
works why well because dog owner extends
the person manager extends the person so
that property will be definitely there
we can navigate to the browser we just
need to refresh and eventually we will
see all three values but it's different
with delegate tasks so notice once you
start typing typescript is complaining
it says well listen it could be either
the person or a dog owner or a manager
so you don't know that 100% the delegate
tasks is going to be there at runtime
this is why we want to set up a function
and we'll start with somewhat
straightforward approach and then we'll
cover why we want to use type predicate
so let's go here with a function my
okaye I'm going to call this is manager
so I want to make sure that it's a
manager and then in the if block I'm
just going to invoke delegate tasks
That's My overall goal so I'm going to
be looking for object because this is
what we're getting back from employee
but same deal as far as the parameter
well it can be one of these three
interfaces okay then as far as the
return like I said for now let's just go
with the straightforward approach where
I'm going to go with Boolean either it's
going to be true or false and I guess
the first gotcha in here is the
return remember previously when we used
the typ guards we did something like
this we went with type of then object
and set it equal to something now is it
equal to what object well all of them
are objects so that's not
specific so if I invoke his manager with
employee this should return for all of
them pretty much the same value let's
try it out we're going to go here with
log is manager then let's pass in the
employee and let's take a look at the
console notice as I'm clicking I'm all
the time getting true so yeah this time
guard is great but it's not going to
work in this case so if we want to check
for manager we want to look for
something
specific and that something specific is
one of these methods and the syntax is
following where we want to go with the
method which will pass in the string and
in and then the parameter in this case
object so now let's correctly type one
of the methods in my case manage people
and now let's navigate to the browser
and again once we refresh we'll actually
see correct
results only if the interface is manager
then we return true and if it's not the
case then we return false but there's
another gotcha so now let's go and set
up if block I'm going to go with is
manager I'll pass in the employee pretty
much our setup and then let's try to
invoke
employee and same deal I don't have
delegate tasks for some
reason let me try to invoke it and again
typescript is complaining so here's the
deal yes our logic over here is correct
but just because we return a Boolean
from this function doesn't automatically
signal to a typescript that now
employees actually type of
manager and here basically yeah we
passed the if condition but as far as
typescript is concerned it it can be
still one of these three types and this
is where type predicate is super useful
and that is a special kind of return
that not only returns a bullion but also
it
asserts the argument to be a specific
type so what am I talking about in here
instead of the Boolean we can go with
object that's going to be the syntax is
and then since I'm checking over here
for the
manager that's the interface I'm going
to use and now typescript definitely
knows that once we pass this condition
this will be a interface manager so once
I navigate back over here going to
refresh once I'm getting back the
manager I'm also logging delegating
tasks okay and at the very end of the
interface section I also want to cover
the differences between the interface
and the type alas so if you're setting
up the object since interface is used to
provide the shape of an object you can
use either of them so if I have object
John with name and age I can either use
the Alias type person or I can use the
interface person now as far as the
differences you see type alas we can
also set up for primitive types for
example if I have number or the union
type number or string and the literal
types you won't be able to do that with
the interface so that's the first
difference again when it comes to
interfaces they're useful to provide the
shape of an object but you won't use
them with the Primitive or with the
literal type now with interfaces we can
merge them together like we covered
before or another word is to reopen them
you won't be able to do that with the
type so with the interface you can set
up the interface you can add some
properties then I don't know three lines
later you can create the same interface
basically with the same name just add
more properties and you're good to go
that doesn't fly with the type that's
another difference now as as far as the
interfaces they can be implemented by
the classes while the type aliases
cannot be implemented in such way so if
you work with classes this is something
to keep in mind you can use the
interface with the class but you won't
be able to implement the type Alias with
the class and lastly remember when we
covered computed properties you can only
do that with type Alias so you won't be
able to use the computered properties
with the interface and with this in
place now we can move on to our next
topic okay and up next let's discuss
Tuple or Tuple in typescript which is a
special type since we don't have it in
JavaScript and essentially it allows us
to set up an
array with fixed
length and ordered with fixed type in
other words it's super useful when we
want to group different types of values
together so for example I have a let
person now this is an array and here I
have string of John and then number of
25 I can set the type in such a way
where I go with my array and then I
provide those values so in this case I'm
going to go with string and number so
now this value is fixed so if I'm going
to try to add something else like hello
typescript is going to complain if the
types are not going to match if for
example I do decide to place 25 over
here typescript also is going to
complain so not only we have fixed
length but also we right away set up the
fixed types so now this value can be
only the string and number now there is
a gacha something I'm going to cover in
a second but for now let's just focus on
this that yes it's going to be John and
it's going to be 25 now you're not
limited to only two values over here you
can set up as many as you want and for
example you can go here with number and
number I mean that's also an option
let's say you don't want to have just an
array of numbers but you want to have an
array with fixed amount of numbers so
let me just go here let's say with
date so in this case it's going to be
number number and number and then
depending where you live either you'll
pass in the month or the day so let's
say I'm going to go 12 then
17 and then we're going to go with
2001 so notice now this is a fixed array
with number number number so again if we
make any changes that typescript will
complain about it now it's useful if
let's say we want to return something
from the function let me go with
function get person and we're not going
to provide any parameters I'm just going
to say that yeah this function is going
to return an array with such types so
string and number so now let's set up
the function body where we want to go
with our array we want to pass in John
and we're going to go with our
25 so now if we have random person now
and that one is equal to a get person we
invoke it if we
log random person and then zero copy and
paste and one in a console we should
have both of those values now like I
mentioned the gotcha here is that even
though when we're hardcoding these
values typescript is going to complain
unless we provide over here this read
only we can actually add items or remove
items from our particular array so how
is that going to look like well let's
say if I go with date.
push I can add the values and typescript
actually is not going to complain about
it now it complains because it's not a
number right so it says well it's not a
number but if I change this to do my 34
everything is going to be fine so I can
set up multiple instances and now if I
loged the date check it out it's
probably not something that we expected
now the workr is to provide this readon
over here so in this case I cannot do
that so once we add this
readon we cannot use anymore the push
pop or whatever methods that's something
to keep in mind now lastly I also want
to mention that we can use the
optional parameters as well so let's
say if I'm going to create a new
instance and I'm going to call this
Susan so I'm going to go with my Tuple
we're going to set up a string number
and in here I'm just going to go with my
optional parameter once I set it equal
to my function notice I can just provide
the string and basically I'm good to go
typescript is not complaining this
should do it for tuples in typescript
and up next we're going to discuss enums
in
typescript okay and up next let's
discuss enums in typescript against
something we don't have in JavaScript
and essentially enums allow us to define
a set of named constants the syntax as
following we want to go with keyword
enum then let's come up with a name in
my case I'm going to go with server
response status since we'll have a
little bit of functionality so we're
going to go with response
status then we want to go with the
curries and this is totally up to you
you can go all lowercase you can
capitalize the first letter or you can
go all
uppercase totally up to you we just need
to provide divide over here the values
and in a second I'll show you what this
actually results
to so first one is going to be success
and then the error now we can add more
but for our example we really don't need
it then let's set up the
interface in this case I'm going to call
This Server response and then the first
property result actually is going to be
type of enum so let's set it equal to to
server response status and then another
one is going to be a data and this will
be an array of strings so now let's set
up a function get server response which
actually is going to return this
interface so we go here with function
get server response let's invoke that as
far as the return type let's set up the
server response so this is equal right
now to our interface and then inside of
the function body we want to go result
and now since this is type enum over
here this is what we want to use so we
go over here with server response status
and notice we either have error or
success again you can use enm if you
want to store some constants and then
later on use it in your project so now
in this case we only can provide success
or the error so let me type this one and
then in order to match our interface
I'll provide data as well I'll say first
item then comma and we're going to go
with second item now I do need to add a
comma over here we do want to invoke it
and set it equal to response
const response is equal
to our get server response let's invoke
this function over here and let's set up
the type what we're expecting so we're
going to look for our interface and then
let's
also log the response just because I
want to show you the potential values we
can set up over here so at the moment we
have success and error and by default
they
actually get the numb starting with zero
and I'll show you what I mean in a
second so first let me just log the
response and notice how the result is
zero
now why is that well because if we go up
over here and we log server response
status we'll see that we have right now
the success and error and the values are
zero and one so it starts with zero then
one and then pretty much the more values
you add well the more numbers you're
going to have now don't be surprised if
you see quite a few values in a console
ENT
at the moment we have four of them this
is something we're going to discuss in
the upcoming video for now I just want
to showcase that even by default you get
those values starting with zero so 0 1 2
3 and whatever you can also reassign
them so for example I can say that
success is going to be equal to a 500 or
I'm sorry 200 and error is going to be
equal to 500 or I can mix and match I
can say that yeah error is actually
going to be equal to this string this
also is valid and again the main point
is that now we have over here this
constant which we can use all throughout
our project instead of trying to make
sure that we type the string or the
number correctly okay and up next let's
take a look at the gacha with enams
which is the fact that when you have
number values it's actually going to do
the reverse mapping
and remember it is the default so if we
don't provide anything we will get that
reverse mapping for example if I provide
over here 200 and 500 if I navigate to
the browser again I have more values
over here in this object so not only
error and success but I also have this
reverse where number is actually a
property and then whatever is my
constant name is set as value now why do
we care well because let's say we want
to iterate over the values in JavaScript
we have object. values and then we pass
in the object in this case we'll pass in
the inum and you'll see that everything
is going to work but it's going to
depend what kind of value we have over
here if we have a number we'll have to
do an extra check so let's go here with
object dot values then let's provide
server response status and we're going
to go with for each so we're iterating
over now I want to grab every value and
we'll just log
it and again since I have the number
values I have this reverse mapping so
now not only I have the number value I
also have this success and error and
it's not going to be the case if
let's say we're going to go here with
success and in here error again
something valid that you might set up in
your code now everything is correct now
we're only accessing that string so if
we have numbers which again is the
default setup so again let me set it up
here as 200 just so we're on the same
page the solution over here is just to
add another another typ guard so if I
only want to access the values they are
type what their number so this was going
to be a string therefore in here I'll
say if type
off and value that was the name of my
parameter if it's equal to a number well
then I want to log it or do some kind of
functionality in this case just log so
we're going to go with console log and
we'll log the value so now we
correctly just access those number
values now another place where we need
to be careful is when we're setting up
the value so notice something
interesting if I have an
enum I have a constant over here and the
value is number then later when I set up
this enum as my type I can still use the
good old number so this is going to work
because again typescript is doing that
reverse mapping however if you have an
enum where the constant value is
actually string this is not going to fly
so just to Showcase that I think I'll
comment this one out so if I have here
200 and 500 if I set up over here this
result to be equal to my enum I can go
to my server response and this is going
to work work so typescript is not going
to complain about it and I can see that
my code runs and everything is awesome
however if again and I promised for the
last time we'll change it around we go
with success and error this is not going
to fly if we navigate back to our get
server response and try to provide the
string value as you can see right now
typescript is complaining so we cannot
assign string to a type enum however
when we use the number value it's going
to work because there is this reverse
mapping hopefully that's clear and now
we're ready to move on to the next topic
okay and now let's work on our next
challenge where we want to define a enum
with the consant of admin manager and
employee Define the type Alias named
user and in there we'll set up the ID
property name as well as the rooll and
the RO is going to be equal to our enum
and also we'll set up the contact which
is going to be a tuple on two elements
the email which is a string as well as
the phone then we'll set up a function
by the name of create user which will
take in the user object as a parameter
and return the user object and then at
the very end we'll call the user object
provide the object object and we'll
create the instance so in tutorial I
think I want to start by defining that
enum here let's call this
user role let me set up my constants
here and I think I'm going to rely on
those default values so 0 1 two and I
guess in this case that's going to be it
only going to be 0 and one two then we
also want to go with
employee after that let's set up that
type alias in this case
user here one by one let's set up those
properties ID is equal to a number then
we also have name is equal to string
we're going to go with roll and in this
case it's going to be equal to a user R
so one of
our three constants and then we also
want to go with contact and we set this
one up as string and string we have
create user function so let's set it up
over here create user and this one is
looking for a user parameter which is
going to be type user same deal over
here we're going to go with user and
from the function we'll return the user
and the last step is to create the
instance so let's go with the user which
will be type user let's call create user
and now let's provide the values
ID name John do then also we'll have a
roll and since we're using our enum
we're just going to set it equal to user
R then Dot and one of the values in my
case I think I'm going to go with admin
one and then at the very end we also
have the contact I want to set it equal
to our array and let's just provide some
values gmail.com comma and then we're
going to go with 1 2
3 four 5 six and 7
89 the very end let's just log it and
pre sure everything is going to be
correct Yep looks like I have the
correct value and with this in place
we're ready to move on to the next topic
and up next let's cover type assertion
which is a way way to tell the browser
what type an existing variable is and
this is especially useful when we know
more about the type than the typescript
does as a side not it's very handy with
dom elements so if these examples don't
seem that convincing in the later
sections we will cover different
examples as well so let's imagine the
scenario we have a variable and I'm
going to go with some value and for some
reason type is any now as far as the
value I'll set this up as a string so
this is a string and then in the next
line I want to get the string length
which actually is going to be a number
so in here let's set it up type is going
to be equal to a number and now I want
to go with DOT length but I want to
assert to a typescript that actually
this is a string so I'll say some value
and not just any type I'll say as string
so the keyword we're looking for is this
as that's the assertion where we tell
typescript that yeah I know that maybe
this is not something you expect but I
know more and I know that this is the
specific
type this is also something that we can
use for example with the Json parse
because it returns any so let's say we
have a type bird now this type bird only
has a name and we'll set it equal to a
string now it looks like I have a type
over here so let me set it properly and
now I'll set up two Json strings and
we'll run pars now in order to speed
this up I will grab those values from
the read meor here so basically we have
bird string and a dog string we want to
set it up over here and now again once
we'll run Json pars you'll see that type
actually is any so let's say I have a
bird object and that one is equal to
Json then parse and now I'll pass in my
bird string so again let me copy and
paste and let me set up one for the
dog and as we hover over like I said
type is any but I don't want type to be
any I actually want this to be a type
bird so if we create an instance or any
other functionality and we set it equal
to a bird object instead of just leaving
it as type any I can go with as and then
my type because I clearly know that yeah
maybe I'm getting this back as type any
but I know that the signature matches
whatever I have here for the type bird
now please be careful you can also do
something like this where you can set up
the dog to be a bird and most likely
that's not the behavior you want so if I
go here with not bird object I'm going
to go with a dog object and I'll set it
equal to a bird I will be able to look
for dog. name but if we take a look at
the dog string it doesn't have that
property so it has the breed so if we go
here with log and we type bird name and
as I said for some reason it's
complaining it says cannot find bird and
yep it's because for some reason I named
it bed so let me go here with bird and
also a dog notice how typescript is not
complaining because
I made a type assertion that yes this
will be type bird even though we can
clearly see that it's actually type dog
now we don't have the type yet but you
get the point so if I navigate right out
of the browser notice how I will get
this unexpected
undefined at runtime and at the very end
let me just show you a use case that I
just encountered when I was working on
my next JS project so in there there was
a enum and I believe the name was status
don't quote me on that and there were
more values but I'm just going to set up
two so we don't have to spend all day
typing and essentially there was a
constant and I set the values equal to a
string so there was pending I believe
interview declin but we're just going to
go with these two so we're going to go
with declined and we'll set it equal
also to a string so I had this enum and
then I was just adding it to I believe
it was the job instance and I was saving
it in a
database now here's the kicker when I
was saving actually in a database I was
saving it as a string because that was
the value for my status pending and then
when I was getting back the value from
the database it was already a string but
I needed to reassign this value to one
of the instances and at that point
typescript was complaining because they
didn't match and if this doesn't make
any sense let me just
showcase let's imagine that we have a
user object and in there I have two
things I have name String and also
status is now going to be equal to a
type status so we know that ually we can
use status. pending status. decline
everything is nice but since these
values are not numbers we don't have
that reverse mapping so if we'll try to
set this value as a string it's not
going to work so now let me quickly
navigate to read me and I just want to
grab these two comments over here again
just so we don't have to type this from
the scratch imagine this scenario now we
save status pending in a database but we
save it as a string so we'll save this
value over here then we get it back from
the database and
now I'm going to go with the status
value and I'll set it equal to the
string value of pending so effectively
this is what I'm getting back from the
database again kind of makes sense
correct because this is the actual
string value now if I'm going to go here
and set up my user instance and set it
equal to my user
type yep I typed the name everything's
correct but if just going to go with the
stat is equal to a status value notice
how typescript immediately complains
type pending is not assignable to this
type so typescript doesn't know that I
saved in the database as a string so I
know for sure that it's the value that's
going to
match the constants here in the status
TPT doesn't know that it just says Hey
listen status here is type status so you
cannot set it equal to a string and this
is where the assertion is useful where I
say yeah it is a string but I know for
sure that is type status so again type
assertion essentially is a way to tell
the typescript that we know what the
type is that we know more about the type
than the typescript does okay and up
next let's cover type unknown which is a
type safe counterpart to type any so
just like type any we can assign any
value to type unknown but the difference
is that before we can use the variable
with type unknown we need to perform
some type checking which again avoids
the unnecessary runtime errors so let me
go to tutorial and in here I want to
create a variable and I guess in my case
I'm going to call it unknown value so
that will be my
name and as far as the type I will set
it equal to unknown so just like with
any I can go here with unknown value and
I can set it up for example to be a I
don't know a hello world so Yep this is
allowed I can also go to a next line and
set it equal to for example array that
is also allowed so let me set up my
array I'm going to go with numbers okay
good and then also we can set it up to
be a number so let me go with 42 and
then let me add some numbers after your
D dot so this is allowed now the
difference is that I cannot go over here
and say unknown value and then set it
equal to a fixed as we can see
typescript complains it says Hey listen
that type is unknown and right away
you're running some kind of method how
am I supposed to know that it's actually
a number and we can run this particular
method I mean maybe it's still a string
so the difference again unlike type any
before we can use that value if it's
type unknown we need to check what is
the type so in this case we can do
following operation I can go type off
and then unknown value and I can check
well if it's a number well then I want
to run my method so let me move this
sucker down and notice now everything
works because in this condition
typescript knows that yeah unknown value
is actually a number now one place where
we'll definitely see type unknown is in
the try catch block because by default
typ scrip is going to set this error to
be unknown now why do we care about that
well what is typically the first thing
we do over here go here with log
and then error and then the message and
notice how T says well error is type
unknown so how do you know that there's
definitely going to be over here this
message property and this assumption
comes from the fact that typically
especially if we're throwing our own
errors over here we use the following
code we go with throw new error and
provide whatever message and in this
case I'm going to go there was an error
so this is is a nice assumption but
please keep in mind that JavaScript can
also do something like this we can go
with throw and some string over here and
I know what you're thinking well there's
no way I'll do that in try clatch block
yeah but you might be running some code
from third party library and at that
point you don't know whether the error
you're going to be getting back is going
to be the instance of the error class or
it's going to be something else again it
literally can be a simple string now to
demonstrate that I will use somewhat of
a silly example where I'm going to set
up the function over here I'm going to
go with run some code so let's imagine
that we're saving an image in a database
or I don't know we're posting some data
somewhere or sending an email or
whatever and in here I'm just going to
set it equal to I Rand them then let's
go with math. random let's invoke that
and essentially if it's less than
0.5 then I want to throw a new error if
not then I'll just throw good old string
so let's set up over here if
else and let's check for random if it's
less than
0.5 then I want to use the
seconder let me set it up over here and
if not then I'll just go with throw and
we're going to go with
some error so let me save this and now
in Tri block let's go with run some code
and effectively in here in a catch we
want to check whether the error is the
instance of the error class and if
that's the case yeah then we'll have
access to the message in this case there
was an error and if not well then we'll
simply log and provide some hardcoded
error and this is essentially what
you're going to do when you're working
with typescript
before you do something with that
message you want to check whether the
error you're getting is actually the
instance of the error class so here in
the cach block we want to go with
error instance off we're looking for the
error and then if that's the case yeah
then tcri knows okay there is a message
property and here we can go right now
with log and and we can set up the error
do message now if it's not the case
since I already have some text I'll
simply log the
error let me log it so now let's
navigate to the browser and check it out
depending on that math random either
we're going to get there was an error or
we'll have that string some error and
again just like any type unknown can be
anything but before we can start using
type unknown we'll have to do some type
checking and therefore this is a type
safe alternative to type any and up next
let's cover type never which is a
special type that represents the type of
values that never occur now I'm not
going to Sugar Code it especially in the
beginning this entire concept might seem
pretty confusing but hopefully after we
cover one of the most common use cases
of type never it's going to be easier to
grasp the main concept of type never for
starters let's just establish that if we
have a variable with type never we
cannot assign value to it so let's say
if we set up a variable some value and
if let's say it's zero if I'm going to
go with type never typt is going to
complain and I'm going to get the same
result regardless of the value over here
so this can be hello world this can be
an array doesn't really matter we cannot
assign any value to type never so that's
the first thing we need to remember
second you might encounter in your own
code Type never if you set up one too
many conditionals speaking from the
personal experience so let's say you
have a type theme over here
and you set it equal to two possible
values either is going to be light or
it's going to be dark then let's set up
a very useful function called check
theme yes we'll say that theme parameter
is going to be equal to our type of
theme now we're not going to return
anything so I'm just going to set it
equal to void and then inside of the
function I'm going to set up two
conditions I'm going to go with well if
theme is equal to and then I'm going to
go with light one and I'm not going to
be particularly original I'm just going
to go with light theme and then let's
return from the function and we already
know that typescript is super smart it
knows that at this point theme can only
be value of dark correct because these
are the only two options but let's
imagine scenario where we do add another
condition I'm going to go with if theme
is dark okay good then I want to log it
but I'll change the value and I'll also
return let me change this one around let
me go with dark theme and notice
something interesting if we type theme
after both of these conditions
typescript says Hey listen theme is type
never because we have handled all of the
possible cases
so at this point in time there is no
possible value for the steam so if you
ever encounter such scenario you'll have
to go back and look at the original
value and also all the conditions you're
setting up because somewhere things are
going south if you are at the point
where variable is type never well then
you already have handled all the
possible cases and what's really awesome
we can actually use it to our advantage
the fact that we cannot assign any
values to never and also the fact that
typescript will immediately assign type
never if we cover all of the possible
conditions as far as our example we're
going to go with enom I'm going to set
it equal to a color we're going to go
with red and blue so those are two
possible values now we can assign it to
a string but there's really no need then
we want to set up a function in my case
I'm going to go with get color name as a
I not I'm just going to set up a switch
statement where we check for possible
values but if you work with Redux you'll
find this example very similar to how we
set up the Redux store so as far as the
type for my parameter it's going to be a
color and inside of this function I
simply want to go with
switch I want to check for my color and
let's set up our cases so at this point
we have two of them so we're going to go
with color. red so if the color is red
what do we do then well then we want to
go with the return
Red so let's set up our
colon
return and we're returning the string of
red and if it's blue well then let's
just change it around so let me select
these
two and let me just go with blue then
let's set up to console logs iess let's
invoke get color name and we'll pass in
color then red and we're going to copy
and paste and set up blue as well and
everything's awesome if we take a look
at the console yep we have red and blue
but what if sometime later we go to a
color and add green and notice
everything is valid not breaking any
rules over here the problem is going to
be here when we invoke
it this is going to
fail but the worst case it's actually
going to fail silently so if we navigate
right now to the browser we can see red
blue and undefined why well because
we're not handling the case over here
and again this fails silently so we set
up nicely an additional enm we correctly
pass it in and then unexpectedly we're
getting an error correct and if you're
familiar with such code you're probably
screaming at me you're like Hey listen
just set up the
default case and throw the error and
you're correct before typescript that
was the approach so let's go here with
default then we go with throw new
error and for now let's just take a look
at the color and all of the is nice but
keep in mind this is again happening at
runtime so yeah we have this default
case where we throw the error if none of
the conditions match but I actually
would like to do that while I'm writing
the code not when my application is
running so we can definitely keep this
one over here but a typescript approach
is to come up with the variable and I'm
going to go with at build time here and
me add another comment and in here I'm
going to go with at
runtime and in here we want to set up
another variable now the name is really
up to you but I'm going to go with
unexpected
color the type will be equal to a never
and I will assign it to the color and
notice how immediately typ script
complains why well because initially we
only had two values so if we go back to
this one everything is
correct I only have this yellow squiggly
line which is totally okay but if I'm
going to add this green one then right
Away tab script is going to yell at me
because now I have one more condition
and of course we already saw that if we
don't handle it over here then
essentially we will throw that error at
runtime so what's the solution well we
go with another case
let's go color
green and same deal just want to go with
the return and return a string in this
case it's going to be a green one and as
you can see the moment we shut up our
cage types doesn't complain anymore
everything is fine because we have three
possible enums and we're handling all of
those cases in our get color name as
well so essentially this is a great
benefit for us where we can check for
those potential errors at build time
instead of just runtime okay and up next
let's switch gears and quickly discuss
modules and typescript now if you are
familiar with how es6 modules work most
of the things we're about to cover will
be a nice review but when it comes to
modules and typescript there are some
GES
we need to be aware of and let's start
with the main one you see by default in
typescript files are not modules they're
actually treated as script in a global
scope so what does that mean well if I
go to a source come up with a name for
example actions TS come up with some
random variables one is going to be
Susan then second one is going to be
something so let something is equal to
something if I create another file or in
the tutorial try to use the same
variable
name not going to be successful so
typescript is actually going to complain
so it doesn't treat this file as a
module so whatever I set up in my files
is actually put in a global scope which
obviously limits the variables I can use
I have Susan over here and I also have
Susan in the actions and therefore
typescript is complaining so pretty much
think of it this way everything that you
put in the files by default again we'll
fix that in a second but by default was
actually put in the global
scope so in order to fix it we have two
options we can go to TS
config and essentially set the property
or we can add the export and import and
the moment we add export and import then
they're treated like typical es6 modules
now also don't be surprised about this
gotcha where let's say in
tutorial you'll try to come up with the
variable with the name of name and you
won't be able to even though technically
in actions we don't have this value over
here you see such name is used in
declaration file again something we're
going to cover a little bit
later and again we have this name
Collision because typescript doesn't
treat this file as a module so
essentially unless we change that
there's going to be some keywords that
we cannot use and this was
super confusing to me in the beginning
because as I started learning typescript
I wanted to use this name variable and I
got this red Squigly line and I was like
what's happening over here why I cannot
use this name one I mean there's
technically no error and again let me
repeat for a third time it's because by
default typescript is going to
essentially treat the files as just
scripts in the global scope so once we
know the issue how we can fix that like
I said we have two options over here we
can either go to TS config and add the
property and you know what let me just
first showcase is how this would work
with Import and Export if we add export
or import statement to our file
immediately typescript is going to
essentially treat this as a module so
for example if I'm going to go back to a
tutorial and if I'm going to go with
import and I believe this one was the
named export so we're going to go with
something from the actions everything is
awesome so notice we don't have the
issue anymore with the global scope
correct so now these ones are scoped to
tutorial and then these ones are scoped
to the actions hopefully that is clear
so this is one approach now what if I
don't want to add Import and Export like
force it in a way well then we can go
over here to TS config and we're looking
for the property by the name of my
module detection and we want to go with
Force so by default it's going to be set
to Auto but we want to force it so in
this case even if there is no export
statement everything is going to work so
notice now of course I have different
complaint because I'm importing from the
actions and there is no export but the
moment I save I can use the name even
though it's technically used in
declaration file which was the issue
before
and I don't have this name collision
with actions anymore as well so I have
Susan over here and the same is in
actions again few
approaches we can either add the
property in TS config or if we add
Import and Export then immediately
typescript is going to treat it as a
module okay and once we're familiar with
the main gotcha let's just see how we
can use es6 modules in typescript and
like I mentioned before if you are
familiar with the main
Concepts this is just going to be a nice
review now before we start typing away I
do want to mention one property in the
TS config which is module and at the
moment notice how we have the value of
es next now this property controls what
module syntax is set up in the out put
code so effectively once the typescript
is done compiling our code so if I
navigate to a playground notice I have
my export statement over here where I'm
exporting some function and this is
going to be the result now if I go to TS
config and change from es next to for
example commonjs and as a sign not if
you're not familiar with
commonjs it used to be the main module
syntax in node.js but even no. JS is
right now slowly but surely switching to
a es6 module syntax and notice the
moment we change it actually this will
be the output so this is a common JS
syntax so if you ever have a use case
where you want to use different module
syntax in the output code just look for
the module property something I wanted
to mention and now just go to actions
and set up few values we want to export
and then in tutorial we will import them
again just to have a nice review how the
es6 modules essentially work just so you
can see that pretty much the idea is
exactly the same first I want to go with
um some kind of function I'm going to go
with say
hello let's set up name equal to a
string and you know what I'll also say
that we're not returning anything from
this function in here we're going to set
up a nice console log we're going to go
with
hello and let's access the name so
nothing
really groundbreaking then let's also
export let person is equal to
Susan and let's also set up a new
student so this will be my object and
there's going to be a type for this
student so new
student I don't have the type yet so let
me just type over here
Peter and age let's set it equal to 24
and you know what let's do set up to
type because I want to showcase how we
can nicely export type so for now let's
just go with
type
student and name is equal to a string
then age is equal to not string sorry
I'm going to go with number and then new
student is going to be type student and
now since I already have two named
exports I just want to showcase how we
can do the default one as well so we're
going to go with export default then new
student and essentially call it a day so
now I want to navigate to tutorial and
one by one let's grab all of those
values since I have the default export
I'm going to go with new student which
is coming from the actions of course we
can use a different name but I'm not
going to do that and then for the name
ones we're going to go and say hello and
also we'll set up the
person one second yep I want to save and
let me open up the tutorial over here so
these are the things we are importing
right now let's invoke say hello we're
going to go typescript okay good then
let's log the new
student and also a person just so we can
see whether we're getting the correct
values and then we'll talk about the
types and how we can export them so
hello typescript I have Peter as well as
the Susan so everything works as we
expect and as far as the types yes we
can nicely export types as well so in
here I can go with export then type
student and then back in tutorial I have
few options I can either go here with
the student notice how I'm getting right
away a nice suggestion or we can also
add over here this type again this
doesn't change anything as far as the
functionality it's just
a common approach to signal that this is
a type we're importing
so this clearly signals to me that hey
this is a type that I can use in this
file so for example I can go here with
const another student set it equal to my
student
type and let me add different values so
this will be equal to
Bob me add an equal sign over here comma
and we're also going to set up the age
of 20 three and then if I log another
student we can clearly see that we don't
have any typescript errors and then in a
console we should have the correct value
now million doll
question what is the correct quote
unquote approach should we set up the
types in a separate file and then import
it or we keep it in the file where we're
actually using the type and as always
the answer is probably not something
you're looking for it really comes down
to your preference yes definitely you
can set up over here a new file call it
types DS and then pretty much every time
you have a
type in your project set it up in the
types and then import in all the files
where you're using that value it's
definitely an option you can definitely
do do that and another approach is to
keep the type in the file where you
initially are using it and then if you
ever have a use case like in our case in
tutorial you export and then grab it in
tutorial and a common scenario is that
you initially just set up the type in
the file and then if you see that you
are reusing it all over your project
then yeah at that point it kind of makes
sense to keep it in one place since the
Imports are going to be easier you won't
have to think about well where is the
actual type located but again as always
it really comes down to your preference
all right and while we're still on a
topic of modules let's also see how
typescript treats JavaScript files so
remember at the very very beginning of
tutorial I mentioned that whenever we
work with
typescript in our case since we're
working with JavaScript files and react
files we need to stick with either do DS
extension or DSX
extension and now let's see how
typescript is going to treat the file if
it's just a JS extension so let's say
I'm going to go with source and we're
going to create the example
JS and let's go with
export some value
that is equal to some value everything
is awesome I'm just missing over here
the keyword in this case I'm going to go
with let and now if we go to tutorial
what do you think is going to happen how
do you think typescript is going to
treat this file let's go with import
some
value and it's coming
from and I don't see essentially it in
my suggestions so I can try to force it
I can say over here example JS but not
going to be successful so effectively
typescript is complaining that it
couldn't find the file now the reason
for that is because it's not a
typescript file so here's the thing
about typescript it pretty much needs to
know everything about your project and
this is something that we're actually
going to come back to when we start
working with the third party libraries
in our project essentially when we start
using the code that's coming from
somewhere else so as far as typescript
is concern no we need to set this one up
as a typescript file so then it clearly
knows well what is the shape for the
data we're getting because at the moment
typescript is like hey I don't know what
are you getting over here I have no info
on this sum value now we can force it
there's a property we can add in the
typescript config just keep in mind that
typescripts ability to infert types it's
not going to be as robust as when we're
working with the typescript file so yes
we can navigate right now to TS config
we can look for compiler options and we
can go with
allowjs and essentially we can set it
equal to true now we do need to add a
Comm over here and now everything
magically Works in our tutorial so
essentially typescript can infer that
some value is actually a string but just
be careful with such approach
effectively since we're working on a
typescript project yes we do want to
name our files
TS because then typescript is going to
know that it's a typescript file and
it's going to have the info on the shape
of the
data and if you'll just set up
JS file without making any changes to
the DS config try to run it typescript
will complain basically it's going to
say Hey listen I'm not sure what are you
exporting what's happening over here I'm
not okay with this so let me remove and
delete this import as well and with this
in place now we can move on to the next
topic and up next let's explore the
tyard options available able in
typescript basically my goal was to
gather all of our options in one place
and since we already discussed most of
them throughout the course this section
will primarily feature challenges so if
you're interested read the steps and
attempt to complete the challenge before
watching the video also for some
challenges I already provided star code
so we can spend more time on the typ
guard Concepts and we're going to start
with the good old type off typ guard and
this is going to be our star code where
we have a type it's either string number
or Boolean we assign it to a variable
and then we just invoke math. random and
then depending on the random value if
it's less than
0.33 then the value is going to be low
if it's bigger than 0.33 but less than
0.66 then it's going to be a number and
if it's actually bigger than
0.66 then it will be a bullion and our
goal is to set up a function in my case
I'm going to call this check value that
takes in one parameter value and the
type will be this value type and instead
of the function effectively we want to
check for all of these conditions for
the string number and Boolean and based
on that we want to do something again it
doesn't really matter what we do as far
as the functionality but we do want to
set up those typ guards correctly so let
me just take the star code just so we
can spend more time on the actual
function let me set it up here in
tutorial and let me start working on the
function so we want to go here with
function
then check value is we'll be looking for
the value parameter and I'll right away
set it equal to a value type now this
function is not going to return
anything at least in my setup and then
let's just set up those typ guards and
remember one of the most straightforward
type guards we have is type off and then
we have bunch of possible values so if I
go here with if then type off I'm
looking for my parameter and I set it
equal to and in here we should at least
get a list now the reason why we don't
have the list is because I have three
equal signs over here so we have this
big in fion function and you can read
the rest so let's start with the string
one over here and I guess since people
are tired with the uppercase when don't
we go with log
and value two and let's try the lower
case somewhere to lower case okay good
let's
return so we want to set up the return
here then let's check for the number and
if
we bypass both of these conditions then
logic tells us that the value is going
to be bullan so I guess you know what
order to speed this up I'll just copy
and paste in this case I'm not looking
for string we're looking for number and
then we want to go with two and fixed
and let's pass in two again we want to
return and at this point it is a Boolean
so let's go here with log and let's just
log the value so let's access the value
and let's invoke the
function so let's go with check value
and pass in the value now let me
navigate to the browser notice at this
point it's a number then I have hello
and at this point it's a Boolean and
with this in place we can move on to the
next typ guard all right and the next
typ Guard we're going to discuss is
going to be equality narrowing now don't
be scared of the fancy name essentially
is just a narrowing which occurs when we
use equality checks now I think will
right away also go with the check for
property typ guard because effectively
we'll have the same starring code so we
have these two types one is dog one is
cat and in here we have the type
property which references the actual
type and also we have the name as well
as the method which is unique to that
specific type and essentially our goal
is to come up up with a function which
is going to check for that specific type
and if it's a dog then we bark and if
it's a cat then we meow and like I
mentioned before we'll pretty much work
on both of the challenges since the
starting code is the same and we just
have multiple options how we can narrow
down one of the types so in tutorial I
want to grab this code notice how we're
using over here the Union as well so now
we have this animal which could be a dog
or a cat so now let's set up our
function which makes the sound so make
sound function we're going to go with
animal so that is going to be our
parameter and that one will be equal to
our type animal and here let's go with
animal and which property is unique well
that will be the type one correct so we
can just say well if animal type is
equal to in our case dog well what do we
want to do we're going to go with animal
and bark because we know that it's a dog
now if it's not the case we already know
that we have animal and our other option
essentially is to meow so if we go over
here and just invoke the
function depending on what we're going
to pass in that's what we're going to
get in the console now at the moment
again there's no function a over here
hopefully it's clear that effectively
we're just narrowing down the types so
this is one option we have also we can
check for
property and how does that look like
well we can go here with function then
make sound same deal animal is equal to
our animal type and then inside of the
function we want to set up if and now
we're looking for a specific
property in the type now in our case
which one is the specific one well you
can actually check for method you can
take a look whether bark exists if it is
an animal then we know that it's a dog
if not then in our case we know that
it's a cat so we're going to go with if
and then bark in so this is a keyword we
want to use in the animal well if it's
the case let's go with animal bark and
if not then we know that it's a cat so
we can run the other method let's go
with meow and let's invoke it so
effectively when we have such setup
these are the options we have either we
can check for property or a method or if
we have a property which has that unique
value for example in this case it's a
typon well then we can also use the
equality checks all right and up next we
have truthy or falsy guard and it's as
straightforward as the name suggests
essentially in here you just want to
check for truthy or falsy value in the
condition and depending on the result
just set up the functionality and as far
as the challenge we want to create a
function in my case I'm going to call
this print length we're going to be
looking for a
string parameter as far as the type
we're going to use the union type so
either it's going to be string null or
undefined and then if it's truthy if
it's a string then we just want to log
string. length if not then we'll just
say that no string was provided and then
we'll just test with few values so here
in the tutorial we want to go with
function print
length let's look for string I'm going
to go with SDR and then as far as the
type either it's going to be a string
either it will be null or we're going to
go here with undefined and if we want to
check for a valid string we simply want
to set up the if block and then pass in
the SDR so if it's truthy if there's
value in a string then we'll end up in
this if block and as far as the logic
we're going to go with s strr and then
length so at this point we know that
it's a string now if it's not the case
I'm just going to go with log and let's
just go with something generic no string
provided even though as I'm looking at
it I mean we're also going to end up
here if there's no value in the string
so technically it's not 100% correct but
let's just go with this one for now
again our main purpose was to set up the
function it inside of the function so
let's go with print length let's go with
hello over here then let's pass in the
empty string then we're going to go here
with null and after that let's pass in
pretty much nothing let's at least try
to do that now we're not going to be
able to since typescript is going to
complain but let's just pass it in just
for our reference so let's say if we
don't provide anything and also at the
very end let's go with print length and
and set up the undefined now let's
navigate to console and essentially
notice if we provide a valid string yep
the result is four so we get back this
length and if not then we just have a
list of no string provided again not
100% correct technically in here it is a
string but it's an empty one but again
these are just Minor Details the main
goal of this video was to showcase the
truthy or falsy type guard in typescript
all right and up next we have instance
off typu which is a way in typescript to
check the specific class or Constructor
function off an object at run time and
this is something we actually covered
very very recently when we talked about
type unknown so therefore in this case
again we'll have two examples we will go
back to trying and catch so we'll
reiterate pretty much everything we
learned in the type unknown video and
also we'll work on the another example
where we'll check for the date so first
let's just reiterate that if we have try
and catch this error is unknown so even
though we have over here for sure throw
new error and if I pass in the message
typescript will complain if we'll just
go with error.
message because there's also
a possibility for different type of
error
essentially we might have an error which
is not the instance of the error class
so therefore if we do want to access the
message first we want to go with error
and then instance off and we're looking
for our error class so if it's the
instance yes then we know that there is
that message if not well then we simply
want to log something some kind of
hardcoded message so let's go here with
log and then let's provide some kind of
string and we're looking for error
object and now we just want to render I
guess the error message so error that
message so now we can access it if not
well then let's simply log something
else we'll just go with unknown
error error and do dot dot again if we
navigate to the browser if everything is
correct we should have this one over
here why well because at the moment in
Tri block I have try new error now if
I'm going to comment this one out or
simply type above and say throw and some
error now I should have unknown error in
the console so again this is something
we covered pretty much few videos ago
now also we can use such setup to check
for date so we can check whether the
input we're passing in is a string or
it's actually the instance of the date
object so let's set up our function
we're going to go with check
input and in
here the variable name is going to be
input basically the parameter name and
then either it's going to be date or
it's going to be a string now from this
function we want to return a string and
now we want to check whether the input
is the instance of the data object if
it's the case then we want to turn it
into a string now if it's not the case
if it's simply a string then we want to
return the input so let's go with input
instance off then data object here and
then let's use input since this is a
date right now we have access to all of
these methods we're looking for get full
year let's invoke this one and we want
to turn it into a string so notice if I
just return this one typescript
immediately complains because this will
be a
but we said that we want to return a
string so let's invoke this two string
so now typescript is not complaining and
if it's not the case if it's not the
instance of the date well then I don't
need to do these acrobatics I can simply
return the input so now let's construct
two variables we're going to go check
input in here let's just pass in new
date and also we're going to go with
some random values as well random
and we'll set it equal to check input
and let's just pass in some kind of
string so
2020 the best year
ever of course in the air quotes and
let's pass in some random date then
let's log both of these values we're
going to go over here with year and
random I'm not even sure whether we are
really interested in the console but
let's just log it and notice essentially
both of them are strings and again the
instance of typ guard is a Nifty way for
us to check in typescript whether the
object is an instance of a class or
created by the Constructor function if
it's the case it's going to return true
if not it's going to return
false all right and up next let's
discuss type predicate function which is
a special kind of function
that not only returns true or false but
also we can narrow down the type and
again this should be a refresher because
we did discuss type predicate previously
as far as the star code let's just grab
this one and then we'll go over the
challenge so here in tutorial I have two
types I have the student one as well as
the user notice this property is the
same it's a string and the only
difference well they have different
methods so one is study and the other
one is login then I use the type Union
to create type person which can be
either the student or the user and then
again I go with my math. random if it's
bigger than
0.5 then I'll return one if not well
then I'll return another one so either
this is going to be a student or a user
and effectively what we want to do is
set up our type predicate function where
not only we check for specific type but
we also want to help typescript by
narrowing down the type uh in my case
I'm going to show you two options how we
can check for specific type but feel
free to use whichever makes the most
sense to you and then after that we want
to use if else essentially run our type
predicate and if it's true we want to
invoke one of the methods so let's say
in my case I'm going to be checking for
student if not then I'm going to invoke
login which is for the user so right
after the person I'm going to go with
function is student at least in my case
I'm going to be checking for student
again this is totally up to you you can
check for user as well now I'm going to
be expecting a person which again can be
either of them for now I'm not going to
set up the return type and as far as our
options well we can use the in operator
something we talked about literally few
videos ago where again we're looking for
something unique in this case either
it's going to be study or a login and we
just go with the method name then in and
then the person since that's our
parameter or we can also use the type
assertion which where we assert that
person is going to be a student then we
invoke the study method and then we
check whether it's defined or not so
again this part is totally up to you for
now again we don't have any returns I
just want to showcase that if we go here
with return and then study again our
method in person this will return either
true or false so
either this method is in the type or not
now if it's the case then we want to go
with person
is the student correct because at that
point that script knows for
sure
that the instance is the type of student
and if that's the case then we can use
the study method now alternatively we
can use this approach where we go to
return Then person and we assert that
it's a
student now what is the method student
has it has the steud one but again just
because we are asserting doesn't
magically make this person to be a
student and therefore in here we still
check we say okay we assert that person
is a student we know that there is a
study property but it also can be
undefined so it's only a student if it's
not undefined
like so so those are the two options you
can use over here and now let's set up
the if blog let's say well if it's a
student then let's pass in the person
what do we do at next well then we can
use essentially our method correct and
if it's not what options we have well
then it's a user correct so we go here
with person and then log in and also
invoke it again a very fancy name type
iate effectively just remember the is
keyword and remember the fact that not
only we're trying
to check for a specific type but we're
also helping typescript to narrow down
that type okay and before we move on to
the next topic I also quickly want to
show you one
gotcha and this involves type never now
technically this video is optional if
you're not interested you can just move
on to the next video but I simply want
to showcase that if we hardcode the
person to be a specific type typescript
is going to yell at us so in here yes we
are setting up that person randomly
correct so we have our random person and
pretty much depending on the value well
we either return a student or a user now
if I set up my person differently let's
say if I comment this one out again I'm
going to go with person I'll say that
this type is actually a person and then
I'll hard code so I'll say name is equal
to Anna and then since I'm creating a
student I'm going to set up my study
method so I'll come up with my function
and I believe it doesn't return anything
so I'll just go with log and study dot
do dot okay let me fix the typos and all
that so now I have this person but I'm
hardcoding this is not any more random
notice TPT essentially right away yells
at me says well there's no way this
person can be a user the other type why
well because you hardcoded to be a
student so yeah I can still check
whether the person is
student so type pred code still works
but in the lse block you'll notice that
person is
never and this brings me back to the
point that I was making in the type
never
video essentially if you have the
scenario where type is equal to never
you'll just have to go back to the
initial place where you're setting up
the variable and also start checking
your conditions because effectively in
here typescript just says Hey listen
there's no way that person can be a type
user because you hardcoded to be a type
student now what's interesting if I
change this around to a
login now the person is actually a user
correct so now I'm hardcoding to be a
user so I have my type predic cut I
check in my condition it's not the case
and now we can successfully get to else
but if I hardcode my person to be a
student then there's no way for me to
get to this pulse block hopefully it's
clear and now we can move on to the next
topic all right and up next let's
discuss discriminated unions and also
let's recall how we can set up the
exhausting check using type never now
again I I know that the name
discriminated Union most likely sounds
pretty scary but essentially it's just
going to be a
property which has a literal value now
as far as the star code this is what we
have over here so we have two types one
is going to be increment action second
one will be decrement action both of
them taking the number the amount time
stamp which is going to be a number
again this is totally random and the
same goes for user string this is
totally random and then we have a type
by the name of action where I use the
union type and I just use both of these
types here so either it's going to be
increment or decrement and then I will
set up a reducer function which is
looking for two things it's looking for
the state so again this is just going to
be some random number and also the
action so what do we want to do do we
want to increase the number or we want
to decrease so let's start setting up
and in a process you'll see why we need
the fancy discriminated unions which
again is just a property with a string
value so for S let's go here with new
state and you know what I haven't set up
the functions so maybe let's start with
this one so we have a
function looking for state which will be
a number so some kind of hardcoded
number and then also the action so
whether we want to increase or decrease
and by how much this is the amount over
here so if we want to increase then byy
this amount and the same goes for
decrease now I'm not going to set up
again anything as far as the
functionality I simply we want to go
with
reducer that's the function and of
course I forgot to add the name over
here my bad so we're looking for
reducer then as far as the initial value
again we're just hardcoding something
random so I'm going to go here with 15
and then when it comes to action well
now I'm going to pass in the object so
either it's going to be increment or
decrement and in this case I'm going to
hard code that user value will be John
we don't have the type yet so let's just
go here with amount of five and then
time stamp well let's set up 1 2 3 4 5
six or something along those lines and
now let's discuss why do we need the
discriminated unions in the first place
well we have two types
and how are we going to check for
specific type I mean we canot use type
off we cannot use in we cannot use I
mean instance off or any of the things
that we covered previously why well
because pretty much they're the same
correct now they do have different
meaning one is going to increase this
state over here and the other one is
going to decrease but in the reducer how
I'm going to check for that action this
is where the discriminated unions come
into play where
we'll have this unique literal value how
is that going to look like we'll
navigate back to increment action and
yes effectively you'll just add here
whatever property name you want in my
case it's going to be a type and it's
going to be equal to increment and now
we want to do the same thing for
decrement so instead of increment we
want to go with decrement so now in the
reducer we want to set up
a switch statement where we're going to
check for the type if it's increment
then we'll increase if decrement then we
decrease and also let's just recap how
we can set up our default case with the
help of type never now typescript is
complaining because I'm not providing a
typ over here so we do need to go with
one of them in this case I'm just going
to going to go with the increment again
it doesn't really matter
since our main focus is on this logic
here in the reducer so first let's set
up the switch one and we're going to be
looking for Action type that's the
property we're interested because it's
Unique to each type over here and again
if we have 10 types yeah we'll pretty
much have to set up the type for all of
them and provide that unique value then
we want to go with case and this case
I'm going to go with increment and as
far as what do I want to return from the
function well let's go with number so
we're going to go with that initial
value basically a state and we'll add
action Dot and the amount that I'm
passing in now we want to do the same
thing for the decrement correct so let's
just change it around and again let's
just recall the issue with the setup if
we add some other type to this action
well it's going to fail silently correct
and therefore we want to set up the
default case and we want to assign the
action to some variable which is type
never because in that case if there's
some other type over here it will
immediately be assigned to that variable
and we cannot assign to type never so
let's just go over here say
default that's going to be our default
case let's also throw I guess quite
typical scenario so throw new error and
then I'm going to set up the template
string and in here essentially let's set
up
unexpected for some reason this is the
biggest challenge as far as the spelling
unexpected action over here type will be
equal to never and we'll assign it to an
action so if actually action is never if
we have handled all the possible cases
we're good to go but if there's going to
be some additional case and we're not
handling right away typescript is going
to yell and in here let's just type
unexpected action and then let's access
the unexpected action again the point
really here is not to run the code I
mean we're mostly focusing just on the
logic over here in the redu sh so this
is how we can set up the discriminated
unions and exhaustive check using the
never type in typescript okay and we
have successfully arrived at the most
complex and confusing Topic in
typescript which is none other than the
generics
in short generics allow us to write for
example functions with any data type and
you can think of generics as a variable
for types now I'm not going to Sugar Cod
it it's not an easy topic the good news
is though that most likely in the
beginning at least based on my
experience you'll primarily use generic
functions or interfaces created by
somebody else whether it be the creators
of typescript or developers of some
third party library and in that case
you'll only need to remember one concept
every time you see those funny looking
angle brackets think generics and let's
begin by taking a closer look at the
arrays in typescript so at this point in
tutorial we should be already familiar
with this syntax so we have three
variables the values are arrays and here
we just say well what is the type for
the array and as we're looking at this
code and we're just focusing on
typescript so please don't tell me that
the answer here is the keyword let as
you're looking at this code what is the
one thing that doesn't
change so what is the one thing that
stays the same and it's kind of pretty
obvious but I do want to start from this
point and the answer is following notice
how the type is changing here all the
time but we're always always getting
this array now of course we can make
this complex we can provide our own type
we can provide the union type whatever
that doesn't change the main idea we're
always always getting back this array
and not only that we can pretty much
pass here whatever we want as far as the
type correct so it still needs to make
sense as far as type and we'll always
get back the array so it's not like I
need to go somewhere and look for string
array no I don't have such type I
literally just have this one universal
one that I can use because if you think
about it how difficult it would be
that not only we need to remember but
also to construct such types let's say
we'll need to have one numbers array
type then one Boolean one and I can go
on and on and on and
on and actually we can examine what type
are we getting back over here so let me
remove this silly text and now let me
right click then we want to go to type
definitions and yes I know we haven't
covered the Declarations yet don't worry
all of that is coming up and you know
what I'll actually pick the third one
because it's going to be easier for me
to show you so let's go here to type
definition and then we're looking for
this declaration one so we're looking
for lib es5 D DS again we haven't
covered them how we have access to them
and all that all of that is coming up
for now but just focus on this code so
notice we have this interface again
something we should be already familiar
with remember we use it to provide shape
of an object the name here is an array
and check it out we have the funny
looking angle brackets and inside of it
we have this T now right away I want to
mention T is convention you can call
this shake and bake you will see that in
a second once we set up our own generic
interface or function or whatever
basically this
represents the notion that this type can
be anything so I can pass here the
string number Boolean my own type you
name it and every time not only I'm
going to get back the array with that
specific type I'll also get all of the
properties and methods that we know
already exist on array so what am I
talking about well we know that length
is part of the array correct we can just
call array. length and we're good to go
so notice we have over here this method
so we can definitely use it and then
let's keep on moving and we'll see again
all of the functions we already familiar
with but here's the kicker for example
pop now if you're not familiar this
essentially is a function which removes
the last element from the array and
returns it but now notice what is the
return here specified for the pop it's
not string number or Boolean or your own
no it's basically this D it's basically
this generic so whatever I pass in
whatever array I
construct well I want to remove that
last type
correct I'm not saying hey this is the
array of strings and now I need to call
specific method to remove the string no
basically whatever type we use to set up
that array well that's the same type we
remove and
notice how essentially
we're saving bunch of the code because
imagine if you would have to set up such
interface pretty much for any type that
we can pass in the array I mean you
would go most likely insane so that's
why we use this variable where we say
okay you can pass in any type and it's
going to get treated the same way we'll
create the array the same way we can you
call the methods the same way so so none
of that changes so whatever type we pass
in well that's the type we're going to
use to operate so hopefully again this
is clear that it definitely makes sense
in a lot of instances to set up the
generic one because you don't want to
set up essentially the interface for
every possible type that you can pass
intoa and now knowing this we can
actually take a look at the second
approach we have to construct the arrays
now I can tell you right away that just
because we know the generics you won't
have to use the syntax so you can still
use this I would say more userfriendly
syntax but I do want to showcase that
since this interface is an array we also
have this option so now let me comment I
guess these ones out you know what let
let me start everything from scratch so
I want to go here with let and again I'm
going to call this array one and and
then as far as the type sorry I'm not
going to go with string I will go with
array and then let's pass in the string
and now as far as the result well that
one is actually exactly the same so I'm
just saying yeah it's going to be an
array of
strings and
again this doesn't change the only thing
that's going to
change the type that we're passing in so
if we pass in the string and of course
course we'll get back array of strings
as well as all the methods that we can
call so if I call the pop on this one on
array one guess what it's going to
remove the last item and the type is
going to be string and of course we can
repeat the same for number and bullion
and with this in place now we can move
on to the next topic all right and once
we're familiar with the main Concepts
let's construct our own let's start easy
let's just go with the function as well
as the interface
so here's the goal we want to create a
function which is going to take any type
and return the same type so one approach
could be following we can go with
function then let me go with create
string as far as the argument I'm going
to call this string basically I'll give
it a type string it returns a string and
then from the function we return the
argument now
everything is awesome but we pretty much
need to return the same function for any
type so we need to create one for the
number for Boolean and rest of them now
I'm not going to create function for all
of the types but you know what let me
just Showcase with a number so let's say
if from this function we want to return
a number this is what we'll need to do
and as you can see this gets annoying
pretty fast correct and we only have two
types so this is what I was mentioning
in the previous video imagine that array
interface if it's not a generic that
pretty much you'll need to copy and
paste and everywhere where you have a
string you'll have to change it to
number and Boolean and then rest of the
types so what's the solution well this
is where we use the
generic I will leave this one for your
reference or you know what actually you
have it going read me my bad let's start
from the scratch I think it's going to
be better we're going to go with
function then let's call this something
generic and I think generic function is
good
enough and we will set up the parameter
we will set up the
logic now I want to set up the variable
for my type so instead of hard coding
instead of number and string I'll say it
can be any type and both my argument as
well as what I'm returning are going to
be that type so we go here with this
angle bracket like I said you can call
this shake and bake just make sure you
use the same name and again the
convention is just to go with d which
stands for type so we go here with t
then we say that yeah argument is
actually going to be this type so I'm
not going to say that it's a string
number whatever no whatever type we have
over here and as far as the return will
also go with the T this is what I'm
returning from this function and now we
just need to set up the logic where we
return the argument so now we
can go here and set up some string value
set it equal to generic function then
since I'm creating a string value this
is the type I want to pass in and then I
just want to provide a string let's save
this and now I can do the same thing for
the number so instead of string we're
going to go with number and instead of
type string will set up the number now
it does need to make sense as far as the
argument so it's not like I'll randomly
pass in the string as you can see
typescript is complaining and we set up
over here the number so now we can use
this function with any type even the
ones that we set up ourselves so this is
not limited anymore to one specific type
this right now is generic function where
we can pass in any type and we'll get
back the same type and while we're on
topic let's also take a look at the
interface so I'm going to go with
interface and let me right away call
this
generic interface same deal if we want
to set up a generic one we already know
that we need to go with angle brackets
let me stick with convention with the T
and then there's going to be a value
property the type will be whatever we're
setting up over here SD that's why they
need to match and let's also set up the
get value
function which is not going to take any
parameters but it will return the same
type and now let's create a new instance
I'm going to call this generic string
which is somewhat funny but let's just
stick with that one since I have that in
a read me so we're going to go with
generic string we go here with generic
interface we say that yep as far as the
type it's actually going to be a string
and now inside of our instance of course
we need to follow the same rules so the
value I'm going to be setting up has to
be a string so we'll go here with hello
world and then as far as get value
one well let's just return this do value
return this do value let's save it and
once I save I have right now the string
instance from my generic interface so
this is how we can construct our own
generic functions as well as generic
interfaces all right and before we start
working on the more complex examples I
do you want to showcase something most
likely as you're looking at these first
few examples you're like I mean this is
ridiculous what is the actual need for
such functions I mean I do understand
yeah there's angle brackets yeah I can
use this T and it's going to work with
any type but in reality this is just
silly okay hold that thought and let's
just set up a a sync function and
remember in JavaScript
what do async functions return they
return a promise so let's go here with
async call this function I'm going to go
with some funk for now let's not worry
about the return or you know what no
let's set it equal to a string do
definitely want to showcase something so
we right away have the error this is
something we're going to deal with for
now let's just return and hello world so
technically it's kind of correct we're
return a string so what is typescript
complaining well
again same functions return what they
return a promise so now let's do the
same thing like we did with the arrays
let's look at the type that we're
getting back and hopefully in the
process you'll see that even though this
might look somewhat silly essentially
this is the foundation that you'll see
over and over and over in document ation
so if I'm going to go here with
result and some funk and we take a look
at the result I mean it says that it's a
string but we clearly have this issue
over here and notice now we have this
the return type of a sync function or
method must be the global promise again
funny looking angle bracket type did you
mean to write promise and hm interesting
we actually have the generic again so
you know what let me remove the return
type for now I'll rely on typescript to
infer a type and now let's click on the
result and type
definition and same deal noce we have
over here this
interface the name is promise and again
it's a generic and yes it has a little
bit more code but not just the general
idea effectively we just get back this
promise and in there we have the type so
the point is that every time we have
this async function we do need to set up
promise as a return type and we just
need to remember that it's a generic so
instead of typing string like I was
doing before we just go with okay we're
returning a promise but since it's a
generic we need to specify the type in
the angle brackets so again the main
point is that yes I know that this might
look silly but keep in mind that this is
going to be the foundation that you see
in documentation as silly as it looks it
actually handles all of the cases that
we're interested because in here I can
return whichever type I need in that
particular instance and I simply just
need to provide the value over here in
the angle bracket so let's say if I'm
going to go with 234 or whatever number
then is going to complain so now I just
need to go over here and say yeah I will
return a promise because it's a sync
function but the type in this case is
going to be a number so yes even
though our first two examples might look
super silly
they use the same concept that you're
going to see later in declaration files
and with this in place now we can move
on to the next topic all right and once
we are familiar with the fundamentals of
generics let's work on a tiny challenge
where we want to set up a function in my
case I'm going to call this create array
which takes in two things it takes the
number length so that just controls the
length of the array so if I pass here
three then I'm going to have three items
if I have pass here 15 then obviously
it's going to be 15 and then the second
thing is going to be the actual value so
if I pass in the string then I should be
getting back the array of strings if
it's going to be number then it's going
to be an array of numbers and hopefully
you see where I'm going with this and I
guess let's start
Again by hardcoding hopefully in the
process we'll
see why we want to use generics but
first let's create a function I'm going
to go with
generate string array like I said we're
looking for two things length is going
to be the length of an array and also
well what is the actual value and as far
as the type I'm going to go with string
now from this function since I'm taking
in the string type I want to return a
string and array now when it comes to
logic I want to create the result
variable this will actually be string
and array and for now it's just going to
be empty array but yes we're going to
store over here the strings okay good
then let's assign result to array so
again we can use our object in there
first we want to pass in the length so
how long is going to be the array how
many items we're going to have over
there and then let's just call the fill
method so pretty straightforward
whatever value we pass over here we'll
add to our result so we'll call fill and
we'll pass in the value and then from
this function since I want to get the
array of strings let's just go the
return and result let's save it and
again everything is awesome but I need
also the same array for numbers booleans
or any other type so now we just need to
make this function generic or you know
what let me just quickly showus that the
code actually works so generate string
array how many items I don't know let's
go with six because I have the example
of three so you probably don't believe
me let me go over here and notice
everything works so I get back my array
it's typ string and I have six items
okay beautiful so now how we can make
this function generic and again most of
the logic is actually going to be the
same the only difference everywhere
where we have the string we just want to
convert it to a generic we want to
convert it to that variable and as a
result we'll be able to pass pretty much
any type
so let me copy and paste instead of
generate string array we'll just call
this create array create array length
stays the same but this one actually is
going to be equal to at and now we want
to set up that angle bracket so again we
set up this variable for a type and we
pass here DT so now everywhere where we
want to reference the type we'll use the
T instead so here instead of string
instead of hardcoding that we'll go with
array and pass in the T then instead of
strings we're going to say that yeah the
result is going to be just an empty
array of this specific type this doesn't
change this doesn't change now we just
want to invoke it and we'll do the same
thing like in the read me we're going to
go with strings then create
array we want to provide string over
here here and far as the value let's go
10 the more the better I
guess let's copy and paste and let's
call this
numbers so
numbers this will be a
number uh let's go with
15 and as far as the value I'm going to
go with 100 so now we just want to log
both of these values array of numbers
and strings
strings let me move this one
up just because don't ask me why and if
everything is correct this is the result
we should see in the console so this is
how we can create a function which takes
any type and returns an array with
specific length of that particular type
all right and up next let's see how we
can set up multiple variable types and
in my case I'm going to use the function
example so we want to set up a function
called pair which takes in two
parameters however the type is not going
to be the same and then from the
function we just return both of those
parameters but again we need to return
the same types so let's go here with
function again the name will be pair we
start with our good old T so we already
know that one but if we have multiple
variables like this we just add a comma
and then provide the value again it's a
convention to go with du and then if you
have more parameters just follow the
logic over here but you can name them of
course differently as well then we're
going to set up our param I guess one so
this one will be equal to T and and then
param 2 is going to be equal to U like I
said from this function I want to return
an array and I want to keep the same
types so this will be equal to D and U
and let's just set up the logic where we
have Pam one comma and then Pam 2 so now
let's invoke it and if everything is
correct we should get the correct result
so we're going to go with the result
that one is equal to pair
and then I'm going to go with number and
a
string let's go with one two three and
hello and check it out typescript is not
complaining so if you have more variable
types add a comma and then the common
approach is to go with you and then rest
of the letters that follow you if you
have more parameters or you can come up
with your own names just make sure you
use the same name in the parameters as
well as the function logic and up next
let me quickly show you that t script
can still infer the type even if we
don't provide the types here in the
angle brackets but just like before we
need to be careful yes if you're
expecting to get back the number and a
string everything is awesome but if by
mistake you pass in some other type it's
not like typescript can magically figure
this out so therefore if you don't pass
in the types You're Expecting just make
sure that you pass in the correct values
hopefully that is clear and as aen this
is something that we're going to see
later when we start working with react
where use State hook actually is a
generic which again if we think about it
kind of makes sense right I
mean we can pass in string into use
state
same how we can pass in the array so
this used State hook needs to accept
whatever value we pass in whether that
is a string number all the way to array
of
objects and essentially since it's a
generic we can technically bypass the
angle brackets so let's say if it's a
string I just let typescript to infer
that yes for sure it's going to be a
string since I'm passing in the empty
string but for example when we're going
to be setting up the Rays typescript is
going to complain and at that point
we'll need to specifically let
typescript know hey is it going to be an
array of strings numbers and in this
case I'm just coming up with some fake
product type so hopefully that is clear
yes typescript can still infer the type
just be
mindful when you use such a pro approach
and also I want to show you how we can
set up the constraint on a type
essentially I can limit the type options
I can pass in so let's imagine this I
have a function of process value
function process value and in here I
have my generic T but I only want to
limit this to a string so the keyword
we're looking for is extends and then in
here we pass in the specific type now in
the following video I'll show you a
different example so don't think we can
only use it here with primitive types
but let's just start nice and easy so
we're going to go over here with the
string then we want to set up a
parameter again I'm going to say that
it's equal to at and you know what let's
say that we're also going to return it
so in here let's log it let's say value
and let's also return the value let me
save it let me call Process value now in
this case I'm just going to infert the
type and I'm going to say hello and as
you're looking at it you're like well I
mean at this point we can simply set up
a function without the generic correct
so I can simply say that yeah I'm going
to be passing in the string and I'm
expecting a string back and you're 100%
correct so with this particular example
I mean there is no real benefit of
setting up the type and then extending
it only down to a string but again it is
a option and in a following video you'll
see a more complex example where
actually it definitely makes sense now
we can also use the union type so
effectively I can go with string or
number and at this point if I call in
process value I'm able to pass in the
number as well so for example I can go
with 12 now if I'm going to go with
process value and then pass in I don't
know true then of course typescript is
going to complain because we can only
pass in string or number in this generic
function and once we're familiar with
the extends keyword now let's see a more
complex example where we have our own
types so let's imagine the scenario
where I have type car two properties
branded model both of them strings then
I create the instance same with product
only in this case the properties are
name and price and I have string and
number again I create the instance and
the same with students so the properties
is the same the first one name it's a
string but then the second one is age
and in here I want to come up with a
function I guess I'm going to go with
print name because why not where I just
want to access the name prop property so
let's go with our function print name
then let's provide the type the generic
in this case we're going to say that
input is also going to be D and we're
not going to return it so I'm going to
go with void now even if we just try to
conso log input that name typescript is
going to complain why because it has no
guarantee that there will be that name
properly so in this scenario we're not
going to extend to a string we actually
need to look for the types which have
that name property correct and in our
case we can either go with the student
or with the product we just set up over
here extends and we go with student so
just like before with string number
Boolean or whatever we can use our own
types as well so now if I go and invoke
the print name in here and if I'm going
to pass in the student everything is
going to work now it's going to fail if
I pass in the product even though it has
the name correct let's try it out so I'm
going to copy and paste and once we
invoke the not print name print name
sorry we're looking for a product of
course typescript is going to complain
because the type is product in this case
so yes we can still use over here the
union type and passing the product but
there's actually a better way because if
we think about it what are we going to
do now we'll look for all of the types
where we have the name and then
essentially just use the union type and
add it to extend I mean technically it's
an option but like I mentioned there's
actually a better way and that better
way is that we can set up an object we
can set which property we're looking for
and then we can pass here in the extends
now we can set it up as a separate
variable or we can pass here directly so
instead of passing in my student or
product types I can simply set up an
object and I can say Hey listen I'm
looking for name property and it has to
be a string so now that script is smart
where it says okay so student yeah it
does have a name so everything is going
to be fine same with the product but if
I'm going to try to call it with a car
it's not going to work because there is
no such property so if I pass in this
instance notice entually it complains
that the name property is missing in the
car so this is an interesting way how we
can use extends not only with a
primitive type or our own custom type
but also we can simply narrow down to
the shape that we are expecting okay and
at the very end of generics let me show
you how to set up default type just
please keep in mind that it's not going
to be super useful in our examples since
we're hardcoding all of our data anyway
basically they're going to be far more
useful when we don't know what is going
to be the shape of our data so let's
imagine we have
interface it's going to be a generic and
I'm going to call this store data I'm
going to say that I'm expecting T and
then inside of it there's going to be a
data and it's going to be equal to an
array of types so whatever we pass over
here then let's set up store numbers so
store numbers and first let's set up the
type so we go with store data then
number and then we set it equal to data
and in here since I want to store
numbers I'm just going to go with one
two three and four okay so this works
but what if let's say I have some random
stuff what if I don't know what I'm
going to have in the array well let's
try it out so we're going to go with
random stuff set it equal to store
data for now we're not going to pass
anything in we're going to go with data
and then we'll set up some random stuff
so I'm going to go with my string over
here as well as the number now store
data is expecting the type so at the
moment essentially we have two options
either we set up over here the default
one then we won't get the error over
here or since let's say I not sure what
data I'm expecting back technically I
can hardcode here any I can say yeah I
mean I'm not sure what values I'm going
to have in this array so I'm just going
to go with type any now if we want to
bypass
this essentially passing in any if we
don't know what data we're expecting we
can simply set D equal to any or any
other default type as a side note you
can go here for example with string or
whatever is just somewhat common to see
and as default type and in that case we
don't need to even provide it so if I
don't provide the type then right away
typescript is going to use any as my
default one again kind of hard to see
over here because we can clearly see
basically what we have in Array but just
to Showcase that I'm not making this up
let me grab the example from the readme
so if you're interested that you can
also copy and paste now there might be
some errors since I don't have those
values over here don't worry about it
too much I just mainly want to showcase
some
stuff most likely you're familiar with
the library called axios which is super
popular to make HTTP requests and
normally the syntax is following where
we go with AOS then the method Now by
default it's get but in here I hardcoded
get as well and we pass it the URL and
the data is
located in the object in data property
now if we take a look at their
documentation we can actually see that
get is a generic what does that mean
well it's looking for the type but if
it's not passed in over here it uses any
so if let's say you just called axios
doget it's going to set data as any so
whatever we're getting back and we can
actually see that if we continue
inspecting the documentation notice
there's also a second one which is r and
that one by default is equal to aio's
response and it uses the type we pass in
so essentially this is another generic
interface which is used as a second type
over here and essentially it uses the T
that we pass in now if we take a look at
the axio response in our generic one we
can see that we're getting back this
data and this is set equal to T but
again the default value is any so for
example if we don't
provide any info on a type it's going to
be equal to any because that's the
default as we can see it's used over
here it's passed down to AIO response
and the same deal in in the interface
now if we set up the angle brackets and
specifically say that Hey listen I'm
fetching this data but I know that
structure is going to be following I'm
going to get back the array of object
and in there I'm going to have name
which is going to be a string in that
case this data will have this shape so
if we
provide essentially a shape that we're
expecting then the Ste becomes that
shape and goes all the way down to data
now if not then they use the default
parameter and essentially set equal to
any now I know it's a lot of code in
here a lot of angle brackets and that
but hopefully it's clear now we can
nicely use type any if we don't know
what shape we're getting back because
again think about it this is an HTTP
request so the shape can literally be
anything and therefore the default one
is any and then if we provide specific
shape well that's the shape we're going
to have here in this data property okay
and while we're still on a topic of HTTP
let's also see how we can fetch data
with typescript now normally I use axos
library with react query simply because
the setup is super straightforward and
react query is really good at inferring
the types but let's start nice and easy
and cover up the straightup pitch API
first and also keep in mind that in this
example we'll just log the result so we
won't set any state or display pretty
much anything in a browser we'll just
check for correct results in developer
tools all of that is coming up just be
patient and wait for the react part of
the course now also you will need the
URL so in the read me I provided a URL
back to my server where we can just
fetch some random tours we were using
this one in my react
course basically build one of the
projects so this is totally up to you if
you want to use this URL feel free to do
so if not if you have some other URL you
you can of course use that as well and
for now we'll just simply set up a fetch
function we will log the result we'll
see the issue if we don't have any type
and then in the following video we'll
have a challenge where you'll have to
set up the type and proper returns and
all that cool stuff so for now let me
just grab I guess the URL so we're
looking for this one over here and we
want to come up with a function so in my
case I'm going to go with
sync function let's call this fetch data
it's going to be looking for URL it will
be a string over here for now no returns
we just want to set up the TR catch
since we have a sync operation it's
always a good start now in here let's go
with response so this one will be equal
to a weight fetch we pass in the URL so
notice how we can right away start using
Fetch and actually we'll cover that in I
believe two three videos how come we
have access to this function without any
issues and typescript doesn't complain
and fetch has this interesting setup
where it doesn't treat for example 404
errors as errors it only treats the
network errors as errors basically if
you'll have 404 over here it's not going
to come up in the catch block so we will
do a manual check where else say if
response.
okay is not set well then I'll throw my
own error again this is just an extra
check we need to do with fetch for
example you don't need to do that with
axio so go row new error then let's set
up the template string we go with HTTP
error and the status here let's go with
status and we're going to set it equal
to a variable
let me access that we're going to go
response that status so now we're
checking even if we'll have 404 error it
will actually trigger the error and we
will return whatever we have in catch
block and now let's access the data
again we're looking for the array of
objects that's what we have here and you
can definitely see that if you navigate
to this URL in the browser
and we want to set up another
await let's go with the response and
Json let's invoke that and at the very
end of the tri block let's go with
return data now in the catch block let's
right away construct the message so I'm
going to go with error message and this
one will be equal to ter operator where
I'll check if the error is instance of
error well then I'll will set the error
message variable equal to error. message
since I know that the property is going
to be there if not then I'll just go
with something generic there was an
error so let's set this one up and then
let's log just so we can see what's
happening we're going to go with error
message here and then at the very end of
the catch block we want to return empty
array so if we're not able to get all of
the tours will return
MTR now I guess for now let's just log
what we have in the data and let's
invoke the fetch data fetch data let's
pass in the URL if everything is correct
in the console we should see this array
of objects and if I go over here and
mess with the URL since I have this
check over here now the response is not
going to be okay and I can clearly see
that over here so we're nicely throwing
the error as well and this is going to
be my error message so this works now
where is the issue well let's go over
here set the tours away to TS so now I'm
essentially assigning this to some kind
of variable and notice something
interesting what is the type well it's
any because typescript doesn't know what
I'm getting back so so yeah I was able
to fetch data I have access to it I have
no issues but this is equal to type any
now why is that such an issue well let's
try doing this let's go towards map we
know that we're iterating over correct
our array and we should have access to
each and every object over there but if
I type tour check it out typescript
immediately complains says okay I have
no info on this this is type any so how
am I supposed to know what is this tour
so we're not getting any suggestions
we're not getting Auto completions
anything like that so yeah I can set
this equal to tour and and
then go with tour. name but I mean this
is not going to be sustainable in the
long run so yeah I can nicely see
everything in browser's console but
since we're working with typescript we
will have to figure out how to provide
the shape of our data to typescript so
typescript knows that Hey listen this
tours is going to be an array of Tours
where I have following properties so I
have ID name info and rest of them and
this is something that we're going to do
in the next video as a challenge all
right and once we see the issue now
let's fix it how well we're working with
typescript so we need to provide the
shape and set up the correct return type
for our fetch data and once we do that
typescript is going to know what we have
there and then we'll have Auto
completion suggestions and all that cool
stuff so here's the
challenge set up to type a hint you can
use the URL as your reference and also
set up a proper return type for the
fetch data again hint remember that it's
a promise correct because it's a sync so
first let me navigate to the browser and
I can see that essentially each and
every object is going to have ID name
info image and price and guess what it's
pretty straightforward all of them are
strings so now I just want to navigate
back to
tutorial somewhere over here set up my
type I'm going to go with type and name
is up to you in my case I'm going to go
with tool
ID is going to be equal to
string then I have the same for name
info image and price so you know what
let me just copy and paste hopefully
it's going to be faster in the long run
so we have info here then we have image
and at the end we also have the price
let's save this and there's two places
where we want to set up this type so
first we want to set it here where we
have the return and I'm also going to
set it over here where I have the data
so I'm going to say that I'm expecting
from this. Json back my array and it's
going to be an array of Tours and the
same over here for my fetch data I'm
going to go with my return and remember
this is a sync correct so what do we
need to pass in a promise promis is what
it's a generic so we go over here with
tour and then we pass here the array as
well now don't worry if it's empty it's
still technically going to match
whatever we have in our return and now
we don't want to set this as any of
course we can actually go back and we'll
nicely see that this is a tour why is
that super beneficial because check it
out if I'm going to go here with log and
tour dot notice I have all of these
properties right away avail ailable I
can go with name save it again the
result in the browser is not going to
change but essentially this is just a
type Safe Way how we can fetch data
where we come up with the type we set up
proper return and after that can start
using this data in a type Safe Way in
our project all right and the moment we
feel good about ourselves that we have
nicely provided the type and Everything
is Awesome we can start using in our
project let me throw you a m grenade so
what do you think is going to happen if
I'm going to remove some Properties or
I'm going to add some extra ones so
let's say if I'm going to go with
something and then I'm going to set it
equal to a bullion what do you think is
going to happen you think I'll have
access to it you think typescript is
going to complain and I guess you can
clearly see that typescript is is not
complaining and actually if I go over
here technically I can even select it
but what is the result I'm getting back
undefined so here's the
kicker yes this is definitely something
we want to do we do want to provide a
correct shape to the typescript but
there's no way for typescript to check
this at
runtime so yes this is super useful for
us to later use in our code you saw
previously what happens if we don't do
that then basically typescript thinks
it's any but also just because we set up
this type over here at build time it
doesn't 100% guarantee that at run time
we'll get the correct results because
this is just build time in here we're
saying yeah this is going to be my shape
so I can type here whatever I want and
typescript is going to be like Hey
listen
you told me that this promise is going
to return the array of Tours and this is
going to be the shape for the tour but
what if the something is actually not
there I mean there's no way for
typescript to check that and therefore
in the following video we'll take a look
how we can do the runtime checks with
the help of extra Library by the name of
Zod okay and up next let's see how we
can validate
data at runtime first off let me just
mention that technically you can do it
manually so in this case yes we can
iterate over data check if the specific
property exists as well as has the
proper type and even though it sounds
super cute in reality it can get messy
pretty fast so instead if you ever need
to validate data in such a way Zod
library is a very valid Choice simply
because it provides bunch of options out
of the box and it's far better battle
tested than our own validation code now
you can use Zod in other scenarios as
well for example in my nextjs course we
use Zod to validate form submissions on
the client as well as server actions on
the server if you interested in learning
more about Zod just visit Zod Dev or you
can follow the link I left in the read
me first thing we'll need to do is
install the library so I'm going to open
up the terminal now I'm going to open a
new window technically you don't have to
just make
sure if you stop the server to start it
up again otherwise stuff is not going to
work so in this window I simply want to
run npm install
and S so now we install this library and
as a side note in few videos we're going
to talk about declaration files so
there's another reason why I'm
installing this Library so we install
Library okay everything's beautiful I
can close this window there's really no
need then we want to import Z from Zod
and essentially it's a named import and
then we want to construct our schema so
let's set this one up and you know what
I can just type it scratch I guess so
let me go over here let me go with
import then Z from and I'm looking for
my Zod Library again if we have
successfully installed should be
somewhere over here notice I have
dependency and there I have the Zod one
so we import the e z and then we want to
construct our schema so this is very
similar to what we have over here this
is going to be shape of our data but
difference well we'll use Zod methods
and this is going to be checked at run
time so I'm going to come up with t
schema and as a side note eventually
we'll set this equal to a different
value but not for now so in here we want
to go with z and then the object is the
method we're looking for so I'm pretty
much saying that I'm constructing an
object and here yes we pretty much want
to provide the same properties and and
as a side note I think I can remove this
something here and this one here as well
for now we'll figure out what we're
going to do there in a second and yes we
want to set up the validation for the
same property so this is not going to
change however in this case Zod provides
bunch of methods now again I'm not going
to go through each and every method in
this case we simply want to check
whether this is going to be a string and
this is super easy I can go with ID and
then Z Dot and then string so this
method essentially is going to check is
it a string or not and if it's not a
string if it's not present then
basically it's going to yell so now
let's copy and paste and we simply want
to provide different values so we're
looking here for name then we want to
get the
info we also want to set up an
image over here so
image um lastly we also have the price
so all of them are strings but the comms
are missing over here that's why I have
the errors so let me set this one up and
then as far as the tour we can actually
infer the type so I'm not going to leave
this for your reference since you have
access to it in a read me but
essentially I can go with type door and
instead of hard coding Zar has this
method of infer and it is actually a
generic and we should be familiar with
this one so notice the syntax
effectively we just go over here with
these angle brackets and then inside of
the angle brackets as far as the type we
go type off and then tour schema so now
we infer this T type and notice pretty
much the result is the same but now
we're nicely getting this from Tor
schema and like I said you have more
options for
example ID has to be a string but I can
also add min max and all kinds of
methods again this is just scratching
the surface and notice how we don't need
to change anything here in return we're
also here in a data but we do want to
right now add some checks at runtime and
in order to do that I'm going to rename
this to Raw data so this this is not
something we're going to be
passing and instead we want to go with
const result is equal to then we go with
our schema it has an awesome method of
array which we can invoke we're not
going to pass anything in and we also
have this safe pars so essentially safe
pars is not going to trigger
automatically the catch block we'll do
it ourselves so we're going to go save
Parts with we pass in our raw data so
now we're going to check this at runtime
actually not only at build time and then
since we have a safe part since this is
not going to trigger immediate error we
want to check for the success property
in the result so if essentially we don't
have the success property over there
then we'll go throw new
error and let's again and come up with
some message let's go with invalid data
for example let's access the result Dot
and we're looking for the error so if
we're not able to parse then we'll throw
the error manually and now where we have
the return instead of data which we
don't have anymore we're going to go
with result. data so that's where our
data is going to be located and again if
we're successful this doesn't change
still getting back that array but
difference will actually check
everything at runtime so now let me
navigate to the browser I don't believe
I'm doing anything so you know what let
me just log the results just so you can
see what we're getting back let's go
with the result notice we're successful
so success is true so we bypass that
error one and then we get back the data
over here so now I can navigate to my
map one and again I have access to the
door so let's log something let's go
with door Dot and again let's access the
name so this works now here's the
biggest difference if I'm going to go
over here and let's say add a property
which I'm expecting but it's not there
will actually get the error so if I'm
going to go with something and set it
equal to whatever number it doesn't
really matter if I go over here notice
how immediately this is going to trigger
the error so success is equal to
false and now I have this error message
in the console and again the cool thing
is that we're checking this at runtime
not just at build time okay and I think
at this point we're ready to talk about
typescript declaration files and why
they're so important and let's start
with a small recap if I were to go to
tutorial
and you know what no let me create a
file first so I want to create types DS
on here I'll write away export and I'm
going to go with export type and
random and here let's just go with name
and string if I were to import this so
import I mean with the type keyword or
without everything is going to work
correct pick because typescript knows
everything about this type random so I
can start right away using it in our
project so far so good but can you
explain to me this how come I right away
have access to the document object so if
I type over here press dot have access
to all of the methods and all of the
properties and of course I'm not going
to double check that so I'm not going to
prove that it's definitely a document
object but trust me the same one and
again good luck trying to build
something without this document object
so how come we have access to it because
I can guarantee you that I didn't set it
up anywhere it's not like I went to the
types and then started constructing the
document type I mean that would be just
a work for I'm not sure half a year so
what's happening over here well you see
when we work with typescript there's
something called declaration files and
the same is going to work for libraries
something we're going to cover in a
second but when it comes to typescript
they get included and then
essentially as we're working with
typescript it already knows everything
about the document so if we go here to a
type definition there is a definition
for this document like I said it's going
to be
giant but good luck
working without the document so in
here there's an info about every
property every method what it's doing
what um parameters the function is
expecting and that sort of thing so in
here technically there is no
functionality that's going to be running
in this file but there's going to be
type
definitions since when we work with
typescript typescript needs to know
everything about the shape of our data
otherwise as you saw with the straight
up JavaScript file it's just going to
complain so I guess first I'll show you
where
the Declaration files are located and
then I'll show you how we can add them
or remove them from the project now as a
side note since we're using the
boilerplate V
application it's already done for us but
yes if you're starting everything from
scratch you can add those things
manually ually Stars if we navigate to a
node modules and typescript which is a
package we're using under the lib notice
this long list well these are
declaration files again once you
navigate over here let me just find
something uh maybe this one over here
right notice you have these type
definitions it's not like in here you
have some kind of function that's
running no but you have clear
description of type definitions so so
again if you want to start using
something from the
Dom you can only do it if there's a type
definition for that something in one of
the files again you'll see in a second
if let's say we don't have access to
these files typescript is not going to
know what is a document or any other web
apis and the way we control that let me
just close the node modules again it's
already set up for us but you can do it
over here in this lib notice this Dum
essentially in the lib you specify the
set of bundle Library declaration files
that
describe the target runtime environment
and notice over here this D well if we
remove it notice something interesting
immediately typescript is going to
complain immediately typescript is going
to say Hey listen what document I don't
know what you're talking about
so essentially we can either set it up
ourselves or we need to have those type
definitions without those type
definitions we won't be able to
essentially successfully build our
project so let me just close this one
and navigate back to TS config let me
add the Dom since I do want to use it
since we're building for the web and
this leads me to the second Point yes
the same works with any Library you want
to use in our project remember how in
previous
video we were able to import Zod from
the Zod library and we were good to go
so notice how again typescript is not
complaining and in fact typescript knows
everything that there is to know about
the import it knows the types it
contains it knows the methods properties
and all that how well let's check it out
again we're navigating to node modules I
want to close this one we are looking
for a Zod in this case and under the lib
guess what again we have the type
declaration files and in there we have
type definition and therefore once we
start using the
library typescript has no issues it
right away knows what the method is
expecting what is the interface and all
that that which leads me to another
Point yes if you're going to install
Library which doesn't have the
Declaration files basically there are no
type definitions you won't be able to
use it now the good news that there is a
repo which essentially
contains the types for a bunch of
libraries but first let me show you what
happens if we install such Library uh
what is the result and again this is
just random example I'm going to use
bcrypt j s which is a password hashing
library and technically this is optional
I mean you don't have to follow along I
just want to showcase something so let
me go to a separate terminal window let
me install it okay I installed the
package clearly see that it's in my
dependencies okay good let me remove all
of this I'm going to go with import
bcrypt Js from and definitely have the
library but check it out so essentially
typescript is complaining there is no
declaration file so same issue like we
had with the straightup Javascript file
and like I mentioned before the solution
is following there is a repo which
contains bunch of types and I left the
link in read me so let me try to
navigate over here and in this repo
under the types you'll be able to most
likely find the library you just
installed because it contains like What
7,802 entries so essentially you have
typescript types for all of these
libraries and the one that we're looking
for in this case is bcrypt JS otherwise
we cannot use it in a project and the
way we install the types is following so
we go with npm install we're going to go
with save dev then at type
and then bcrypt JS so our specific
Library let me grab this line of
code and the moment we do that
typescript is going to know everything
that there is to know about this bpjs so
if I'm going to go over here type dot
notice I have access to all of the
methods the import provides hopefully
it's clear why typescript declaration
files are so important when we're
building the typescript project and with
this in place we can move on to the next
topic okay and up next let's cover
typescript config file where as the name
already suggests we can configure our
typescript setup now if I'm being
totally honest I actually find this
topic super boring and therefore I'm
planning to cover only the properties
which in my opinion are the most
important ones but if you are interested
in specific property or maybe you feel
like a rebel and you want to explore all
of them feel free to utilize this link
in the read me so this is the link that
you're looking for as you can see it
guides us back to
documentation and you can start
scrolling and you'll see that this is a
giant file where pretty much you can
find everything that there is to know
about the DS config again big picture
this is where we control our typescript
configuration I just want to mention
that we have this include and in here we
point to where the typescript files are
going to be located so in our case where
it is well it's in the source this is
where we're setting up our project then
we have compiler options and let's start
with the target one over here and with
this one essentially we control the
output code so navigate to a typescript
playground notice I have this export con
and then the arrow function now if my
target is a JavaScript language version
which has the arrow function already
then as you can see the output code is
going to be pretty much the same but if
let's say I change this to
ES3 notice how it didn't have the arrow
function therefore we get good old
regular function so this is what we
control over here in the Target now as
far as the module
remember with this one we're controlling
what kind of module syntax again we're
going to get back in the output code in
the lib this is where we were
controlling the Declaration files that
we're getting and pretty much after that
the one that we're interested is the
strict one so this is this flag which
controls how bunch of the errors and the
warnings are treated so if we're going
to go with false then bunch of the
things that technically should fail are
not going to and we'll be able to build
the project now if we set this one to
true then we have the strict type
checking set to true and then for
example we have this no unused locals so
if I were to go to tutorial and come up
with let something is equal to something
notice how I get this warning that
something is declared but I'm not using
it well if we go here and set it equal
to pulse or just remove it then
essentially we'll have no warning
message anymore again just a example of
one of the properties that we can use
this concludes the TS config and with
this in place we can move on to the next
topic and up next let's quickly cover
class syntax in typescript now if you
don't use classes in your project feel
free to skip this section Al together
since most likely you'll see very little
benefit and first let's start with a
recap that classes in JavaScript serve
as blueprints for creating object and
they also have this special method
called
Constructor which is automatically
called when we create a new class
instance with the new keyword
and this keyword inside of the
Constructor refers to the object being
created so in this case I have a class
notice we need to use the keyword class
then the name is book now the convention
is to go with uppercase but technically
you don't have to and it has a
Constructor it's a typical method
basically we can pass here pams and in
this case I have title and the author so
every time I'm going to go new book and
pass in the values they will be set
inside of this object inside of this
class instance and in order to set those
properties I need to go with this dot
then the name of the property in this
case title and I just set it equal to a
value just being passed in so in this
case it's deep work and then the author
name now since we're working typescript
notice how we have few red Squigly lines
how do we fix them for STS we we need to
set up the annotations over here in the
Constructor so what is going to be the
type of the title and author and here
let's just go with string and string and
of course we can use the Boolean we can
use the number pretty much everything
that we have learned up to this point
but here's the kicker I still have the
red squigglies inside of the Constructor
and you would think okay we can go over
here and say that this is going to be a
string and number or Boolean but when it
comes to classes and typescript we
actually need to go inside of the class
and explicitly set the type for the
properties we are setting inside of the
Constructor so in this case since I have
two of them I have title and author yes
I need to go above my Constructor and
essentially set this one equal to a
string and the same is going to go for
author so I set both of them up and then
notice now I don't have the red
squigglies
and I'm able to create those instances
again result is going to be exactly the
same I will still have my instance in
this case de work with the title and
author properties the difference now
typescript is happy as well so I'll be
able to build my project just like a
normal JavaScript we can also set
instance properties or they're also
referred to as default properties and
essentially the idea is that we set this
property inside of the class instead of
the Constructor and then they get
automatically added to all the instances
we create now how's that going to look
like well imagine we have this checked
out property and it's a bullan and
initially it's always going to be false
so yes definitely we can go here with
this Dot
checked out and again notice we're not
passing anything in a Constructor it's
going to be set by default and I'm going
to go with false so now I can navigate
over here and say checked out and set it
equal
to Boolean correct so this is going to
work but since I'm not passing this as a
parameter we might as well set this one
up as a default property so I can just
move this line of code and where I have
the checked
out yes I can still keep it as Boolean
and set it equal to false but we can
also rely on the fact that typescript is
going to infer this value so this is up
to you you can go like this or you can
set up the checked
out like
so equal to false for example or true
and then typescript will immediately
infer type now again just like other
times when typescript infers the type
just be mindful of potential pitfalls
you might face and if let's say we're
going to go with deep work and checked
out we should see the value in the
console so at the moment it's false and
let's say if we decide to set it equal
to true that's also an option so let's
go with deep work checked out and let's
set it equal to true now since it's a
Boolean we can definitely do so now it's
equal to true but if I'm going to change
it to hello world of course this is not
going to work typescript is going to
complain because it is a bullion so this
is how we can set up default properties
in classes in typescript when we work
with classes in typescript we also have
this read only
modifier which does exactly what the
name suggest
essentially if we add this read only
modifier to any of the properties we
won't be able to modify them for example
if I'm going to go to my title add read
only yes I can still read the value for
example I can go with deep work and
title and for some reason I keep
forgetting to set up my
logs so we can still nicely access the
value problem is going to be if we try
to change it so if we go here with deep
work. title and set it equal to
something else so this is not going to
fly because now we have this read only
modifier added to the title property
also in typescript we have private and
public
modifiers which control whether we can
access the property or the method from
the outside now as a side note by
default everything is public therefore
if we go with deep work and type do
notice we have access to author checked
out and title but if I'm going to
navigate over here and let's say
set checked out to private notice how
still will go deep work and now I only
have access to author and title so yes
of course I can go over here and say
public just keep in mind that's the
default Behavior let me just set it up
so I'm going to go with with public over
here and also as a side not you can
combine them so notice in this case I
have already read only four the title
but I can also say that this is going to
be a public one now typically the way we
control some private property is by
setting up some kind of method which we
can call from the outside just to
Showcase that let me go with the
method and I'm going to call this check
out
then let's set up the functionality
where I'm going to go with this dot
checked out and I'm going to set it
equal to true so as you can see I'm
still able to access the property from
within the class but like we just saw we
were not able to see the checked out
value from outside so in this case I can
go with deep work then let me call the
method check out out and now if we'll
take a look at the Deep work again in a
console the checked out should be set
equal to True correct so let's navigate
back over here and notice of course the
value right now is true so this is
typically how we would access the value
we set this equal to private so we
cannot access it from the outside but
then we set up a method which actually
controls this value and just to hammer
home that we can mix and match I'll set
up few more methods one is going to be
is checked out where we're just going to
check the value and then I'm going to
set up the private method so again this
is a bit of Overkill but I'm just going
to add this public one over here as you
can see that's the default Behavior
everything is public then we're going to
go with another one where we're just
going
to check what is the value so we don't
need to take a look at the console so in
here I simply want to return this Dot
and checked
out and then also I want to set up the
private one where we're going to toggle
so this will be a private method toggle
and let's come up with the name status
that sounds like a good one hopefully I
have no spelling errors and from this
function I simply want to return the
opposite value so I'm going to go with
this Dot and we're looking for checked
out now since this is a private one
again I'm not going to be able to call
it here where I have my instance instead
where I have the checkout one I'll just
set it equal to this dot so now I'm
accessing the private method and I'm
invoking the toggle checked out status
like so and now let's just navigate over
here I guess let's clean up our code a
little bit and and let's just invoke few
functions so for STS let me go with deep
work we have checkout that's the one
that we want to invoke and after that
we're going to go with log and again
we're looking for our instance and now
we want to check the actual status and
notice over here this is set equal to
true so by default it was set to false
then I ran the checkout method which
essentially just toggles the value and
then I logged in a console that it's
equal to true now let me try this one
out let me run it two times and now this
should be set equal to false because
we're just toggling back and forth so
this is how we can use public private
and read only
modifiers in classes when we work with
typescript and up next let's see an
awesome shortcut we can use which is
going to say was quite a few lines of
code now for starters I do want to clean
this up since I want to discuss Getters
and
Setters in the upcoming videos and I
think it's going to be too much logic
inside of one class and also let me
remove the first two properties as well
as all of this code over here in the
Constructor so the shortcut is following
at the moment notice if I go with my
deep work and type dot I don't see
anything correct since we didn't set the
properties correctly but what we can
also do is add readon public or private
modifier in front of the parameters and
if we do that it will be automatically
set as a property with the value inside
of the instance so let me show you what
I'm talking about we go here with read
only and yes even though
it might seem redundant since by default
technically this is public if we go here
and set up the public this will be set
in my instance now we're not going to
use this value but just to Showcase that
same is going to work with private I'm
simply going to go over here and say
some value and let me set it equal to a
number so now if I go to my deep work
right now and type that notice I
immediately have access to author and
the title so this is the shortcut we
don't need to use this anymore over here
we don't need to explicitly set these
properties in a class we simply can use
either read only or public or private
and effectively immediately tcri behind
the scenes is going to set those
properties with the appropriate values
when we create the instance now since
you might not believe me about the Su
value let's come up with some random
function let's just explicitly say that
this is going to be public and I'm going
to call this get some value okay and
then we'll return this Dot and some
value so notice inside of the class I do
have access to it so let me call get
some value and we do want to place it in
a con log I guess so get some value
let's invoke this let's set up our log
let's move this inside and the moment it
says
undefined because I did not provide the
value okay so notice of course it's
missing so I have some value and since
I'm looking for a number I'm going to go
with
45 so once we log right now everything
is correct so again this is an awesome
shortcut we can use
in the Constructor we can add one of the
modifiers and this will automatically
set those properties in our instance and
up next let's work on the example with
Getters and Setters which are special
methods that are access like properties
more specifically let's take a look how
we can combine them with the private and
public
modifiers which we covered in the
previous video
so one cool thing that we can do with
the getter is to set up a computed
property so essentially I can create the
property on a fly now in order to create
the getter or the setter we want to go
with get or set eord then we want to
come up with a name so this essentially
will be a property on this deep work and
in here I just want to compute some
value so in this case case I'm going to
go with the template string first I'll
access the title and I'll combine it
with the author this dot author let's
save it and now we want to go with our
deep work and notice we have essentially
this info property now since we're
returning the value I keep forgetting
that we want to place this inside of the
log and in console now we have title
followed by the author again what's
super cool is that we can create this on
a fly so I can just come up with the
property then do my computation and I
didn't need to set anything in the
Constructor or above the Constructor and
the same way we can set up the
setter the keyword we're looking for is
set and in this case again I'm going to
control that checked out property first
let me start with a set name now just
like
good old
method we can provide over here
parameters and in this case I'm going to
call my parameter checked out now we do
need to provide a type and then inside
of the setter we're going to go with
checked out and we'll set it equal to
our parameter value and then let's
navigate to the console log and right
after that let's invoke our Setter so
we're going to go with our instance then
and set our name and in this case again
this is the property so we set the value
now if I'll try to go with hello and
notice how typescript immediately
complains so let me go back and yep I
want to go true and now I don't see
anything in a console since I'm not
logging let me try one more time where
I'm going to go deep work and if
everything's correct the checked out
should be equal to true and we can use
the private and public as you can see
again by default everything is already
public but let me just showcase if we go
here with private now we can only invoke
this inside of the class so this is not
going to work let me comment this one
out and let me set up two more
Getters one is going to be for the
checked out value and in the second one
will actually we use the check out
method a lot of checkouts so let's go
over here with get now as you can see
the name can be exactly the same because
one is a Setter and other one is a
getter by default it's going to be
public and then from this one we want to
return checked
out and now Just for kicks let's set up
a getter but inside of it let's invoke
the setter just to make it more
confusing so let's go here with public
even though again technically it doesn't
change anything in this case I'm going
to go with some info we're not going to
pass anything in and in order to access
our Setter our private one we want to go
with this. checkout set it equal to true
and then after that we want to return
and since I want to return the same
value you know what let me copy from the
info and and let me just
overwrite in here so now let's navigate
to a console first we want to go with
log I guess we're going to go with deep
work then some info so this is going to
set our checkout equal to true and also
return this value and also
let's copy and paste and set up one more
and in this case I'm looking for my
getter the checkout one and once I
navigate to a console as you can see at
this point it's false then I get back
the
same info the title followed by the
author and at the very end we can see
the checked out value which is now equal
to true and that's how we can use
Getters and Setters with public and
private modifiers and up next let me
showcase how we can implement the
interface by the class and if you
remember the video types versus
interfaces it was one of the things
which we could do with the interface but
we cannot do with the type so let's
imagine we have the interface and the
name is I person which essentially
stands for interface person because
there will be a class of person let's
come up with some random properties so
we're looking for string then also we
want to set up the age number and you
know what let's go with greet method and
it's not going to return anything and
it's also not going to take any
parameters then we're going to go with
class let's come up with the name in my
case person and we go with this
Implement which essentially is promising
that it will provide all of the
properties and methods defined in in the
interface so in this case we're looking
for I person that's the interface I want
to use and in here let's go with the
shortcut which we covered before so I
can go with public now what is the name
it's a string correct so let's set up
and also we want to go here with public
age now this will be a number we're not
going to set up anything in the
Constructor well we don't have to we
still have a red squiggly line because
there is no method so right after
Constructor let's go with greet it's our
function and let's just log some stuff
over here in this case I'm will go with
hello my
name is Slim
Shady and this is name and also I
am this. age let me access this. Ag and
we're going to go with
years old now we do want to set up our
instance so let's go with
con and hipster we're looking for a new
person let's provide a name Shake and
Bake and as far as the years well let's
go with 100 and then at the very end
let's invoke
hipster GRE and if everything is correct
we should see the text in the com so so
that's how we
can implement the interface with the
class again something we canot do with
the good old type Alias okay and once
we're done with tutorial let's put our
typescript knowledge to a good use and
create a small tasks application as far
as the setup for this project I'm going
to set my code editor and browser side
by side but you you don't have to it's
just my preference since that way I
don't have to switch screens like
gazillion times also I will set up a new
page in my case I'm going to call this
tasks
HTML keep in mind technically you can
build everything in index HTML I just
think that it's going to be easier if we
separate the tutorial from the project
so here's what we want to do navigate to
the route again please don't set this
one up in the source we want to create a
new file and I'm going to call this
tasks HTML now I will create a basic
HTML structure and in the vs code
essentially we just do that by getting
the exclamation point I believe I mean I
haven't created the straight up HTML
project in so long that I already forgot
so yeah basically we want to click shift
and back tick and notice we get the this
suggestion from EMT that you can create
a HTML structure now in my case I'm
going to call this tasks app or tasks
then also there's going to be a link for
CSS so that is coming up and in here for
now let's just say tasks app let's save
it now this is totally up to you you can
navigate in the browser and just stay
there or we can actually go to to main
DS and notice we have both of these
logos well at the moment these links
navigate somewhere externally basically
back to typescript and vat and we can
actually change this around where I'm
going to go with forward slash
and
tasks and of course if you named your
page differently please make sure that
the H matches and I'll do the same for
this one so now once I click on one of
them I'm going to navigate to the tasks
app now I'm not going to set up the link
back I don't think there's any need for
it for now I think we can close the main
one but we will return to it and also
let's create an Source tasks DS so this
is going to be our typescript file where
we'll set up the logic let's go with Ds
now in this case we're not going to
import that in the main DS we actually
want to go there directly to
tasks somewhere here the bottom of the
body we want to go with
script then we're going to add type
module and now let's look for
Source we're looking
for tasks I believe yep that was the
file and I always prefer to set up some
log just so I don't run around like a
headless chicken looking for a bug but
maybe there's an UT wrong or something
along those lines now for some reason
yep everything is fine so I see over
here the tasks so I know
that my logic works then let's navigate
uh back to tasks
HTML and now above the script
effectively we want to set up the
structure for the application so I just
want to add some HTML elements now this
is totally up to you but I also provided
some CSS just so it looks a bit more
presentable now you have two options you
can either get it from the final folder
so navigate to the final
repo look for typescript tutorial and
then more specifically look for task CSS
so I didn't want to add this code in the
main CSS file so we're going to create a
separate file for that task CSS and then
just grab that code or you can nicely
navigate to the end of the readme and
just copy this code again there's a
bunch of Base Styles so let's not worry
about the CSS too much as far as the
actual CSS for the project there's not
that much code but I'm not going to go
over it because this is definitely not a
CSS course so just select everything
inside of the back dick where you see
the CSS
then we want
to go I guess let's set up in a source
doesn't really matter we're going to go
tasks CSS copy and paste and now where
we have a tasks HTML we want to set up a
link we're looking for the CSS one and
basically it's in the same or it's not
sorry it's not in the same folder we're
actually looking for t
CSS so once we add that I mean at the
moment most likely we won't see anything
but once we add our elements we should
have a nice CSS as well and with this in
place now let's set up the structure and
I'm not sure whether I mentioned that
technically the CSS part is optional so
I mean it's not going to affect any of
our logic our application is just going
to look tiny bit more representable then
we want to go with tasks of some kind of
value as a sign note we might need to
refresh yep now everything works now I
can see my tasks over here then let's
create a form now we won't have the
action but I do want to add the class
and even if you're not using my CSS
please make sure that you use the same
classes or if you use a different class
make sure that you remember that when we
are setting up the
logic then let's go with input inside of
it the type is going to be text then we
want to go with another class and we're
going to go with form input save this
okay this is what we should see then
also let's add a
button type will be equal to submit okay
beautiful let's add a class name
BTN let's call this add task okay again
I'll have to refresh and then right
after the form we have anord list class
let's go with list we're not going to
place any items so we will place the
items dynamically with the help of
JavaScript and then at the very end
let's just add a test button because
there's something we need to discuss
first so technically this is not going
to be part of the project but it's super
important we cover two things and
therefore we're going to go here with
the
button so we're creating the good old
button let's add a class of test BTN and
let's just right click me let me save
Let me refresh and this is what we
should see in the browser and if you
have the same result now we can move on
to the next step okay and before we
start typing away let's address these
two important points first when we use
Query selector we actually get back the
element which is the most General Base
Class that only has the methods and
properties common to all kinds of
elements so that's Point number one
second there's also potential for null
and we also need to address that and no
we cannot build this project unless we
cover both of these things extensively
now once we do it should be a smooth
sailing so first let me just showcase
the two important points
if we go with cons button we know we
have access to a document correct
because we have the Declaration files
and document has this awesome method
called query selector where we just pass
the class in this case and we can select
the element and everything is awesome
but as I hover over the button notice it
can either be an element so it's going
to be an issue if I try to
get some properties and methods that are
only specific to buttons which is
actually going to be our second point
and also it can potentially be null now
why do we care about that well let's say
if I want to go with BTN and then Dot
and event listener it's not going to
work well technically it's going to work
because typescript is going to fix my
code but notice it's only going to work
if we go here with this question Mark so
this is one approach how we can fix this
because as far as typescript is
concerned there's no way to tell whether
yes for sure we're getting back to
button unfortunately again this is built
time this is not
runtime so typescript is like okay
you're selecting the element from the
dumb potentially well this can be wrong
correct and in that case you're not
getting back the element you're actually
getting back null and we need to handle
that also don't be surprised if in few
cases and I sign not yes we'll cover
that
actually when we talk about the element
point you might need to do more checking
you might need to do something like this
where you go with if button and only
then run the code so this is one
approach how we can handle the case
where element is null and yes every time
you'll want to do something with the
element you'll essentially need to first
check whether the element actually
exists now another approach to deal with
the null issue is by setting up the non
null
assertion operator so effectively in
here I'm telling T script yo I know for
sure that the element exists over here
and in that case notice I can go here
with BTN then Dot and then add event
listener and I don't need to use anymore
the optional chaining and the same is
going to work if I'll try to run for
example disabled on a button I won't
have to check
for the element whether it's actually
present so in here I'm just telling T
script listen I know a bit more about my
project than you do and I know for sure
that the element is there and actually
if we take a look at the main TS I
believe it was over here now don't worry
about the code after essentially they're
just dynamically inserting the elements
and all that notice this one over here
where they go with document query
selector they grab the development
they're looking for the ID over here and
then they just tell typescript Hey
listen we know that the element is going
to be there now how do they know that
well we take a look at the index
HTML notice this ID it's app correct so
you have two
approaches you'll see both of them used
extensively as far as your project it
really depends if you like this approach
where essentially you let typescript
know just be mindful if the element is
not going to be there then of course you
will have runtime errors or or you can
use the optional chaining and then here
and there you might need to actually
check whether the element is present so
that's the first point that I wanted to
address now the second one is following
I use over here this nonn assertion
operator okay everything is awesome but
what if I want to run disabled method I
know that the button has this particular
method so let's say I go here with BTN
Dot and then I'm trying to type but I
can see that it's not present so
something is off why I have such issue
well remember we are getting back what
we're getting back actually an element
which is the most General base class
from which all
elements in a document inherit now this
one the element has only the methods and
properties common to all the elements so
where I'm going with this well there's
going to be instances where you select
elements and you need a specific method
or a property which is only on that
element and this is the case the button
I know it has disabled one and I know
for sure that I definitely want to use
it but I'm not able to because I'm
actually getting back the element now
let's take a look why is that a case
let's go here to type Ty definition and
notice the query
selector so query selector surprise
surprise is what a
generic now it's looking for the type
and notice how there is actually type
constraint where it says yeah you can
pass in the element but it needs to
extend from the element so this is a
more interesting case for type
constraint instead of our string and
number our still EX examples actually
this limits the element to the element
and not only that notice how it actually
provides this one as a default and what
does that return it actually Returns the
element we passing over here or it
returns null so all of the things we
learn we can now nicely use when we
inspect the documentation so now it's
very easy for us to look at this
documentation and be like okay so we do
need to provide the element we want to
select it needs to extend from the
element and if we're successful we're
actually going to H it back so now let's
navigate back and in a query selector we
want to set up the angle brackets and
then we want to look for
HTML button and element so that's the
one that we want to pass in so now we're
not getting back the element or null
we're actually getting back our HTML
button element so now if we start typing
notice BTN disabled and we can nicely
set it equal to true now before I show
you the type assertion option which is
another approach you'll see let me just
remove this non null assertion operator
and showcase that here and there you'll
have to actually check for the button so
remember our second option where every
time we will use a method for example ad
event listener we need to add the
optional training which as a side note
is already done by typescript in this
case in this case in the case of
disabled it's going to be a little bit
different so if we'll try to do that
typescript is actually going to complain
it's going to say hey L and you canot do
that so instead we'll have to check
button and then we can set it equal to
True again this just brings me back to
the point that we have two options over
here and we can also always add this
exclamation point and as far as the
second option if we don't want to pass
here in the generic we can also use the
type assertion so let me just go here
with disabled and let's set it equal to
True again
and let me remove now once I do that
typescript is going to complain and
another approach that you'll see is this
one where we select yes we're getting
back the element but then we use that
type assertion and we say yeah actually
this is going to be HTML and then button
element now I personally prefer the
other approach and that's why throughout
the course you'll see that one but
definitely don't be surprised if you see
something like this in the code base
this is also an option we can take where
we select the element and then we just
use the type assertion and you have the
example in the read me so I guess I can
just remove pretty much everything over
here because we'll start everything from
the scratch and we'll start working with
our form so you know what let me clean
this up we also don't need that silly
button over here since we covered two
important points and now we're ready to
move on to the next step okay so let's
start working on our project and in this
video I want to select three elements I
want to select the form I want to select
the form input as well as the list so
form input is where we'll get the value
We'll add the event listener on the form
so every time we submit the form we will
grab the input value and also we want to
get the list since every time we'll
provide here a task if the value is
there then we'll basically add it to our
list and also this is where typescript
is going to come into play we'll need to
set up our type so this is something
interesting every time you work on a
typescript project yeah pretty much one
of the first things you'll want to do is
to start at least setting up the shape
of your data this is at Le at least in
my opinion biggest differences between
the regular project and a typescript one
you'll always always have the types or
interfaces somewhere because typescript
needs to know about the shape of your
data so let's start I guess
by selecting all three of them I'm going
to go with task form now I'm not going
to use the nonnull assertion
operator throughout the project I'm just
going to use that optional chaining so
we're going to go here with do docent
then query selector I do want to set up
the angle brackets and I'm just going to
say that this will be a HTML form
element or
no then let's go with the class and
we're looking for the form and I believe
I forgot to mention you see there's no
way for typescript to know that this
definitely is a form that's why we need
to provide over here this form element
so it cannot magically go to the HTML
and figure out that since we're using
the form class then for sure we're
selecting the element which is actually
a form that's why we get back this
generic element and that's why we need
to use the generic to provide what is
the element we're actually selecting
hopefully that is clear const form input
is going to be the next one we're going
to go with document query
selector then will provide the
HTML input element so this is the
element I'm looking for input element
okay good and then the class is Dot and
then
form input
now I think I can make this one so
everything is in one line I'm pretty
sure we can see everything that's
happening I mean you know what no let me
make it like this and then
Also let's go with const task list
element and this one will be equal to
document then query
selector let me add the angle brackets
as far as the class we're looking for
list and over here we want
HTML ul and list element and my
apologies I'm just going to be kind of
randomly moving the this stuff over here
don't worry we shouldn't have issues
with the later code it's just these
select lines then let's create the type
and effectively we will have a task with
description which is going to be a
string and is completed which is going
to be a bullan so let's set up this one
type
task then let's go with the description
set it equal to to a string and yes as a
sign not you can set this one up as
interface as
well it's just my preference to go with
typ aliases and we're going to go with
Boolean and
then I'm going to set up an array of
tasks so this is where we'll store the
tasks and as a sign note eventually
we'll grab these tasks from the local
storage as well so think of this as the
state for our applications so we're just
going to go with tasks it's actually
going to be equal to an array of
tasks and for now it's just going to be
empty array okay and now let's start
setting up the functionality so we want
to add event listener on a form we're
going to be listening for submit events
we do want to prevent the default so we
want to handle everything with
JavaScript and after that inside of the
Callback function we want to grab the
form input value if some value is
provided will actually wipe everything
clean and return and of course before
that we'll have to do quite a bit of
logic and if there is no value then
we'll just set up the alert so let's set
everything up we're looking for task
form again we can rely on typescript or
we can manually add this optional
chaining operator ourselves then we're
looking for ad event listener like I
said we're looking for submit and again
notice how helpful typescript is so
right away provides all the possible
events that we can use over here for now
we will provide call back directly but
in the following video I'll show you the
Goa we need to be aware of remember we
have access to the event now if we hover
over we can see the that actually it has
a type of submit event something
important we need to keep in mind and
then let's go with event we're looking
for prevent default and we just invoke
it so now we'll handle everything with
JavaScript after that let's grab the
form input and more specifically we're
looking for the value property which
again is on the form input I'm going to
give it a name of task description let's
set it equal to form input
same deal we don't have this non null
assertion operator so again we can just
rely I guess on typescript or in this
case it simply complains so we'll just
need to add this optional chaining so
now we're grabbing the form input value
if we have something in there if the
user has provided something then we'll
do a list of things if not then go with
alert and
we'll just say please enter a task
description again it's not going to be
the most complex application ever let me
refresh and notice if I don't provide
anything essentially I just get this
alert box now if we are successful again
there's going to be a list of things
that we will
do but once we're done adding a task to
the list once we're done rendering the
tasks and updating the local
storage at the very end regardless we
want to set the form input value back to
an empty string and we want to return
since I only want to hit this alert if
no value has been provided now also for
time being you know what let's just log
here let's just say task description so
if I provide some random value check it
out I have it here in the console if not
again we have this alert box and what
this in place now we can move on to the
next task okay and before we set up the
logic to add new task to our list let me
showcase the event object gotcha and as
I know this is something you'll also see
in react section of the course so pretty
much the main idea is going to be
exactly the same and it is following you
see if we provide over here call back
function directly everything's awesome
typescript knows that yeah it's actually
a submit event but it's not going to be
the case if we set up the reference so
can go here with function create task as
a say not I don't think I'm going to
keep it so I'll just set it up and
eventually remove it but this is totally
up to you of course you can also keep
this code if we're going to go over here
and basically take all of this
logic like so everything should work
correct we have access to the event and
now we can just replace it well let's
see let's go with create task and check
it out so typescript essentially saying
that event right
now has the type of any so this is the
case where if we're setting up
functions and providing them as
references here when we're listening for
events then yes we'll explicitly need to
provide what is the type so in this case
we're looking for submit event and once
we do that again our logic is going to
work I can provide some value over here
and everything is awesome and the same
is going to work with the empty value
and yes the same you'll have to do in
react now in there the code is going to
be more complex but the idea is the same
if you're listening for some kind of
event and you set up the logic directly
in a callback function yes event will
have that correct type straight out of
the box but if you're setting up a
function which you're then using as a
reference it's not going to be the case
something important to remember okay and
up next let's see how we can add task to
our list now in this video we're not
going to set up the logic to render any
tasks on the screen that is coming up so
most likely we'll do right after we are
able to add task to our list and in here
I want to First create function I'm
going to call this add task and as far
as the parameter it's going to be a task
but this is where we set up the type so
we definitely say that we need to
provide the task and we're not going to
return anything from this function and
as far as logic we want to go with task
I'm sorry tasks and then push and we
want to add our task so whatever we
provide over here then we want to
navigate back to our if block and you
know what let's add three comments we'll
say add task to list then second one
will be render tasks and then we also
want to update the local storage so all
of that is coming up for now inside of
the if block I want to construct a task
so if I have a text I want to go cons
task is equal again to my type my task
type and I want to set it equal to
description this will be equal to task
description so this will be my string
and then as far as the completed one we
will hard code so go with is completed
and we'll always always set it equal to
false so once we create task now we can
invoke add task and pass in a task and
since I have the correct type everything
is good script is not complaining and we
can actually log the tasks here so let's
go here with tasks let's add something
so let's say first task and check it out
now I have my array with my first task
if I go with second task it's not going
to be surprised if we have two items in
the array and with this in place now we
can move on to the next step okay and up
next let's render the task on the screen
now we will call actually render task in
two places so for now we'll only call it
here in a task description block so if
we're successful we'll just render it on
a screen but also once we're able to
grab the tasks from the Lo local
storage will iterate over and render all
the tasks on the screen so think of it
this way not only we want to render the
task once we add new one to the list but
also when the user first navigates to
the page or we refresh we want to grab
the tasks from the local storage where
they are nicely saved and we want to
render them on the screen as far as the
function first we just set up our
keyword I'm going to call this render
task and again it's looking for a
parameter but parameter has a specific
type and it's equal to task then inside
of the function first I want to create
the element and in order to do that I
need to come up with the name in my case
I'm going to call this task element then
we go with our document it has a method
of
create
element and we just need to provide what
element we want to create so either we
scroll down or we just type Li and now
we successfully create the list element
then we also want to add the text
content basically it's going to be the
value for our task description the
property is text content and we set it
equal to task so whatever it's passed in
and
description and then at the very end
remember we have our list somewhere here
that's the one if
it exists if it's not null then we want
to add this element to the list so we go
with task list element up in child again
typescript Auto formats for us and just
add this optional chaining and then we
pass in our task element so now let's
navigate up where we have render tasks
and we want to go here with this
function pass in a task and now let's
try it out if we're successful
we should see the task on a screen so
let's again go with first task and check
it out we successfully created the
element on the Fly same is going to be
with second task and all the tasks we
add to the list all right and I think we
are at the point where we can add local
storage to our project because it's nice
that we can render all the tasks we add
to our array however if we na away or
just refresh notice how essentially we
lose all the tasks since they're just
saved in the memory now before we do
anything I actually want to make sure I
have nothing in a local storage
otherwise I mean I might get some weird
bugs so let me navigate to my local
storage and just clean everything again
Let me refresh I have nothing in there
so now again I can make this one
smaller and as I said I'm looking for
the console okay good
and now as far as the functionality we
want to create a function called update
storage and in there we will use the
local storage more specifically set item
method and we'll need to provide the
value and just stringify our current
tasks so in my case I'm going to do it
over here so we go with function let's
call this update storage and as a yes
we'll call it in multiple places so
update storage
as far as the parameters well we're not
going to pass anything in and as far as
the functionality we're just going to go
with local storage then let's go with
set item as far as mining it's going to
be tasks then comma and then we're going
to stringify the tasks as a sign note
yes pretty much every time we will add
the task to our list
or when we click on the checkbox and we
edit the task when we set it equal to
completed or we uncheck that yes
effectively we will overwrite all of the
values that we have in the local storage
with this new one so grab the tasks and
overwrite with the current
values now when do we want to call it
well for starters we want to do it over
here so we're going to go with update
storage let's invoke that and you know
what I will actually open up
a bigger window I think it's going to be
easier to see so that's my
tasks let me open
up application okay good and then let's
go with first task again Yep this is
what we have over here notice tasks and
I have a d and if I'm going to go with
second task now this is going to get
added to the array so this should cover
when we add the task to the array so
this should cover the form submission
now we also want to handle when we load
the page so at the moment we always set
it equal to an empty array but we want
to change that and order to do that we
will come up with a function called load
tasks now you can set it up with all of
the functions but I'm just going to do
it over here since in my opinion it's
going to be easier to see the entire
functionality we we are looking for a
return and from this function we want to
return an array of tasks so an array and
type is going to be the task now inside
of the
function first let's grab the tasks from
the local storage so we're going to set
it equal to stored tasks that is equal
to local or I'm sorry not load local
storage it has a method of get item and
we're looking for the tasks now here's
the kicker just like previously this can
be a null and we definitely need to
handle that so in here when we set up
the return we're not just going to go
with store tasks actually we will set up
optional training and we'll say hey if
there's a value okay awesome parse it so
we're going to go with store tasks
because keep in mind we cannot store
essentially objects in the local storage
we can only Only Store strings that's
why we went with Json string ify and now
we want to parse that value but we only
want to parse it if we get something
back correct if not well then we'll just
return empty array and now where we have
the tasks we'll actually go with load
tasks we will invoke it and since
potentially now we can get some tasks
from the local storage we also want to
iterate over and render the tasks so for
every task we have in the local storage
in our array we want to call render task
method so I mean somewhere after the
tasks we want to go with the name so
tasks then dot we're looking for for
each and we simply can pass in the
render task now let me showcase
that
essentially it's pretty much the
same as we have over here so notice we
can either go tasks and for each and
then pass in the call back function or
you simply provide the reference to
render tasks and now let me navigate to
the browser and if everything is correct
whatever tasks we have in local storage
once we refresh we'll see them in the
browser as well all right and at the end
of the project let's also add the
checkbox to our list item and every time
we click on checkbox we'll be able to
control this is completed so by default
it's false but then once we click on a
checkbox we can actually toggle that and
I think I'll try to cover the part eight
and part nine in this video hopefully
it's not going to be too long STS we
want to navigate to render task and at
the moment we're just adding the list
item to our list but we also want to add
a checkbox to the item and then add that
item to the list hopefully that makes
sense so let's go here with checkbox we
have const task checkbox that will be my
variable we're looking for document then
dot then we want to create the element
and this is going to be the input so not
list item we're looking for the input
and then we'll set the type to be equal
to a text box so we're looking for task
checkbox type
and we set it equal to checkbox then
let's set check equal to is completed
Again by default it's going to be false
so let's go with task checkbox we have
the checked property which controls that
and we want to set it equal to task and
then is completed and now before we add
task element to our list we also want to
go with task
element so task element then
upend child and we want to pass in task
checkbox and check it out now we have
the checkbox at the moment it's not
doing anything since we don't have any
functionality but we'll change that
right after we create the checkbox I
also want to add the event listener and
the event we're going to be listening
for is going to be change so before we
add it to a task element element let's
call
toggle
checkbox we're looking for our task
checkbox that's the element then add
event listener we're going to be
listening for change event we're not
going to access the event and as far as
the functionality we want to go with
task and then is completed set it to the
opposite since we're going to be
toggling and the way we do that is
following so we go with exclamation
point and task is completed so we set it
equal to the opposite and then we call
update storage so now once I click and
you know what let me showcase that on
big screen again let me start from the
scratch just so you don't think that I'm
cheating over here and if we take a look
at the tasks okay this is what we have
is completed is equal to false but then
once I click notice it's set equal to
true so when I refresh I get back the
same result this concludes the tasks
project hopefully everyone enjoyed it
and up next we're going to take a look
how we can use typescript in react all
right and once we're familiar with the
typescript fundamentals let's see how we
can use typescript with react before we
begin let me just mention that I assume
you are already comfortable with react
so things like components State most
common Hooks and some of the popular
libraries if you are confused about some
react topics please pause the video and
utilize some external resources since
our main focus is going to be on
implementing react with typescript
otherwise this part of the course will
easily turn into a react tutorial in
order to follow along with this part of
the course you will need a star project
which is the second folder in the main
course repo so if you have not already
done so get a hold of the repo either by
downloading or cloning it and once you
have the main repo on your machine open
the second folder in your text error so
get a hold of the
repo open up your text eror and then
just access the second
folder now it is a note app so same deal
we want to start by running npm install
first and also or you know what I'm not
going to set up such command because
here and there students complain that
such command doesn't work on their
operating system so first let's just run
npm install and then we want to go with
npm run run Dev and if everything is
correct again you'll have the
application on Local Host
5173 and this is what you should see on
the screen and if that's the case we can
move on to the next step all right and
let's start by taking a look at the
files and
folders as well as the assets I provided
so we have node modules over here this
is where we have all of our dependencies
we have the public one this is where we
can set up some public assets a source
folder again this is where we'll do all
of our work but in this case we're going
to be working with react so we'll create
components and all that cool stuff we
have the eslint file also a g ignore
again this just provides info what files
and folders are going to be ignored by
The Source control index HTML this is
where our root component is going to get
injected so for example if you want to
change the title feel free to do so a
package Json so in here you can take a
look what extra libraries I installed
and also we can see that we have a Dev
one so that spins up the dev server and
also same deal we have over here a build
command and before vit builds the
project what do we do we compile our
code then we have the good old
typescript configuration file and also a
few more configuration files for V and
also the node one now you'll also find
the readme over here and just like in
the first part of the course we will use
this readme to set up the challenges to
take a look at the examples I also
provided some links to useful resources
and all that cool stuff and first thing
that I just want to mention essentially
this project is a straight up beat react
TS boilerplate application the
difference I just added some assets to
it and removed some boiler plate files
that's it so if you're going to run npm
create V latest react typescript so this
is the name of course you can change it
then the double dashes template and
provide react DS effectively this is the
project you're going to get back and
like I mentioned before most of our work
we're going to do in a source
so let's just navigate over there for
starters just like
traditional react application we have
main DSX so this is where we inject our
app basically our root component into
that div with the ID of rot now also
you'll notice few Imports but we'll
discuss it
later I mean these are just Imports for
some extra libraries we're going to use
then we have the app DSX so this is
where all of our components are going to
meet you can also call this the root
component and we have a final and a
starter and the way I set it up notice
these are all the topics we're going to
discuss and this is going to be our
starting point and in here you'll find
the complete code so
essentially pretty much every time we'll
start working on a new topic we'll just
import the specific folder because if
you notice all of them have index DSX so
this will be the default import that's
just a note thing and then as we're
moving from topic to topic we'll just
change the path over here now for all of
them you'll just find this
standard component where I have few
heading twos and basically I'm just
displaying some text on the screen so
all of them pretty much will be the same
but of course once we're done the topic
there's going to be more files more
logic and rest of the good stuff and
just to Showcase how it's going to look
like let me navigate to app TSX we want
to go with import then let's come up
with the name in my case I'm going to go
pretty generic I'm going to say
component from and now we want to go to
a star forward slash and then again we
have all of these topics and as you can
see they are numbered so we'll start
with
return topic and then all the way to
tasks so let's go with 01 return notice
again we don't need to provide the file
because all of the folders have already
a index DSX and then we want to replace
it over here we want to go with
component and then render it on the
screen again at the moment it's not
going to change that much because we
haven't set up any logic yet and
basically as I'm moving from topic to
topic I'm just going to change over here
the path and then if you want to test
something of course you can import the
component from one of the final ones as
well now also something I want to
mention the idea with the react and
typescript is following if we want to
set up components basically react the
stuff we need to go with DSX so that's
the extension now if you just want to
set up some logic some good old
JavaScript logic just like we did in the
first part of the course we just go with
Ds so whether you want to set up some
hooks file or utils file or types file
that's the case you'll go with Ds but
the moment you set up the component you
want to go with
TSX hopefully I clearly explained how
our setup is going to work and if you're
looking at the other files over here in
the source one we'll discuss them
essentially as we progress with the
course content for example the hooks the
store so all of that is coming up and I
guess lastly let me just mention that
yes I did provide some index CSS just so
our examples look a bit more presentable
but again this is totally optional and
with this in place we can move on to our
next topic which is going to be
the component returns in react all right
so we have the correct import again
we're looking for Star 01 return so
that's where we want to navigate and our
first topic is going to be the component
return now let's establish a few things
for starters what are react components
they are functions correct and what is
the one thing that we know about
function returns and
typescript well it's the fact that
typescript infers the return type so if
I hover over notice how typescript sees
that essentially this is a component and
the return is jsx
element so what does that mean well if
for example I'm going to forget to set
up the turn actually typescript is going
to yell at me so notice once I save I
have red squiggly line in app DSX and if
we hover over we can see that component
cannot be used as jsx component because
it returns
void and few things I want to mention
first it's super helpful because when
you're working on a bigger project I
mean having no return sometimes can be
tricky to spot as far as the error go
and second one this is something that I
will probably repeat 10,000 times during
the second and most likely also the
third part of the
course code error is going to be your
best friend the moment you hover over
the squiggly line or in
general the events and state values and
all that it will immediately pretty much
give you all the info you need so in our
case let's say if we go back over here
and set up the proper return we can
clearly see that typescript infers the
jsx element which leads me to another
Point can
we explicitly write jsx element in here
as far as the component return yes it's
absolutely an option we can go over here
even though it's already inferred we can
say hey you know what I'm going to go
over here with jsx element we save it
and since in this case I am returning a
jsx element there's no issue pretty much
it's the same deal but keep in mind what
if in your component you decide that
you're going to return a string well now
it's not going to fly because now I
already have here an explicit return
where I say hey I'm going to return jsx
element and what about null What if I I
have some kind of logic and I'm going to
go with null again same deal we cannot
do that because we have explicitly over
here this jsx element now if you don't
have that typescript is smart typescript
can infer that hey in this case it can
be either hello either jsx element or no
so again this really comes down to your
preference one option you can simply let
the typescript to infer a type and at
least at the very basic scenario it's
going to help you to avoid this case
where you don't return anything second
option you can start hardcoding over
here explicitly what are you expecting
back from this component just keep in
mind as your logic changes you'll have
to adjust because if you're just going
to write all the time jsx element well
typescript is going to be confused so in
this case let me just hardcode it but
for most part I just let typescript to
infer a type so I'm going to go over
here with jsx element that's going to be
one option I'll say Hey listen it can
also be null and also well let's just
set up a string type let me save it and
now notice Ty script doesn't complain
everything's fine because I have the
explicit return and the options that I
have inside of the component match to
whatever I have over here in the list so
that's how we can set up component
returns in typescript all right and up
next on our list we have I believe props
so first let's change the path so we're
looking for 0 to props let's take a look
at
the browser yep we have react typescript
and props so looks like everything is
correct and essentially in here in the
component let's just provide some values
so we're going to go with something
generic for example name and the ID
which is going to be actually a number
so 1 two 3 and immediately once we add
those values typescript will complain
because again it's like setting up a
function providing the arguments but we
haven't set up the parameters so
typescript doesn't know what to expect
so let's navigate right now to our props
index DX and let's take a look at the
multiple options we have for props and
essentially the first one is the inline
one remember in react props are gathered
in this object which we access either by
just the structuring over here where we
go with the curly braces or we go with
props now I'll show you the other option
a little bit later for now let's just
grab the object the props object and
let's
explicitly take a name and the ID so
those are the two values we're looking
for but before we can do that since
we're working in a typescript yep just
like regular function we'll need to set
up the type and the first option we have
is basically set up everything in line
now I can tell you right away that it's
most likely not going to be your
approach especially for bigger projects
where you have components with bunch of
props because it's just going to be very
messy so yes in here it will start nice
and easy but in a second I'll show you
also another approach that we can take
so in here we just say Hey listen name
is going to be a string and the ID will
be a number and the moment we do that
typescript should be happy it just
complaining that we haven't essentially
used it yet now notice how everything's
fine in the component for some reason
it's complaining over here so let's try
to use these values and let's see
whether that makes typescript happy so
I'm just going to change it around I'll
say adding one now that one will be
equal to name and we're looking for our
name value and then the second one will
be Hing one and and we'll just provide
the ID so let's go with ID and then
let's access that let's save this and if
everything is correct we should see name
Peter and whatever ID
provided again we just go back to the
fundamentals section where we learn that
every time we have a function we need to
provide info to typescript what is this
function going to receive as far as the
argument and since props are essentially
arguments that we pass in when we
construct the
component we need to provide the type
annotations and what's really cool let's
say that we're using this component in
multiple places in our project if for
some reason I'm going to forget provide
one of the props notice how immediately
typescript is going to complain so I
won't have to realize this error at run
time as I'm building the project let's
say that I'm setting up this component
somewhere and I just forget that I also
need to provide the name typescript will
immediately let me know that something's
wrong and actually the same works if I
decide that the name is actually going
to be title I mean it's quite common to
have a component and you think that yeah
the name for the prop name is awesome
but then you realize that hey you know
what actually prop name should be titled
let's say I do that notice how
immediately in all the places where I'm
passing in the wrong prop it's going to
light up so again imagine scenario where
you have this component in multiple
places in your project immediately you
know that something is wrong again
something super super cool where you
don't need to run around like headless
chicken and then look for those
instances you'll immediately know where
you provided the wrong prop so let me
set it back to name and ID and up next
we're going to discuss alternatives to
inline type annotations okay so our
initial setup works but what if we have
a long list of props or let's say we
want to reuse these props well in that
case we can either set up the type or
the interface again this is the totally
up to you I'm going to stick with type
just because it's my preference I'm
going to call this component
props and in here we just want to
provide pretty much the same values so
actually you know what I can just cut it
out remove these curries set it equal to
and
then where I have my D structuring I
just want to set it equal to my
component props save it and since I
don't see any red squiggly lines I'm
good to go now also please keep in mind
that
alternatively you can just reference the
props so in here I can say yeah props is
going to be equal to component props
instead of the structuring name and ID
and then every time I want to access one
of the values I can go here with props
ID and props name again this really
comes down to your preference Some
people prefer the props option and some
people prefer this option as long as you
don't have the red squiggly lines as
long as typescript is not complaining it
does really come down to your preference
and the same goes for the type or the
interface so if you want to use the
interface over here you can definitely
do so if you prefer type it's definitely
an option as well and while we're still
on a topic of props let's also discuss
the special children prop which allows
elements and components to be passed
into other components so if I'm going to
go to app
PSX and set up my closing tag as well
and then let's say add a heading to with
a hello world typescript is going to
complain because I haven't specified
that I'm going to provide the children
prop now the name is exactly the same so
that doesn't change we just go over here
with children and yes we do want to
render it somewhere in our return as
well but now M dollar question what is
the type and essentially we have few
options we can hardcode it ourselves and
the type we're looking for is react node
and we can import it or we can just go
to react Dot and then react node so for
example this is one option we can take
where we go with react
Dot and then react node so that's the
type we have access to and the moment we
do that we fix the first error but
notice right now typescript is
complaining because since I set up my
children prop in the props component
it's also expecting the same thing over
here and one easy way how to fix that is
to just make this one optional just like
we covered through during the
fundamentals part so I can just go here
say that yeah children might be provided
or not and if it's provided then it's
going to be a react node now also a
quick side note just like with vanilla
JavaScript actually during development
everything is going to work even though
we have the error but please keep in
mind you won't be able to build the
project unless you change some
configurations and
allow the project to be built with the
typescript errors hopefully that is
clear so let me go back to this optional
property and let me show you another way
how we can handle the children prop
alternatively we can also import a
special type from react which is called
props with children so yes we have
access to a declaration file where there
is a type called props with children
which actually is going to handle
the children prop for us now in order to
import it we're going to go over here
with import now I will add this type
remember technically it's not a must
then we're looking for props with
children and this is going to be coming
from react and if we hover over we can
nicely see the type
definition and this is where I would
encourage you to stop the video and go
over this logic
and try to see whether you're able to
understand everything that's happening
under the hood since we have covered all
of these things during the fundamentals
part and again reading such type
definitions is going to be a good
practice for us not only to jog our
memory as far as typescript but also to
understand what is the specific type or
function or I don't know property
actually doing and if we take a look at
the type definition we can see that
props with children is a generic which
again kind of makes sense
because it's going to be used in a lot
of situations so there's going to be the
case where the component props has one
shape and then in the second component
the shape might be totally different so
again a very good use case for generic
Now by default it's actually going to be
set equal to to unknown so this will be
the default value and then notice how
they use this intersection type so
essentially whatever is passed over here
is just combined with what with children
property which is set equal to optional
so it might be passed might not and the
type here is going to be equal to react
node or it's going to be equal to
undefined so let's try it out
I think I'm going to leave this one for
your reference so let me just copy and
paste let me comment out first one over
here and then instead
of setting up the children property
ourselves we'll just go with props with
children and then we'll provide this
value over here so effectively it's
going to look like this we're going to
go with props with children remember
it's a generic and it's looking for that
type and the moment we do that as far as
the result notice we get back whatever
type we pass in and it's just combined
with this children property and with
this in place now I can go to the app
remove the heading 2 or provide the
heading 2 to the second instance and
everything is going to work and
typescript is not going to complain so
again when we work with children prop we
have few options either we can
explicitly provide the value of react
node ourselves or we can import the
props with children which essentially
does the same thing behind the scenes
all right and once we're clear on
component returns props up next let's
talk about state so first we want to
change the import and and this is
actually going to trigger some
typescript errors so I think I'm just
going to go with good old component for
now so let me render the component yep
typescript still complains because we
haven't changed the import so we're
looking for a 03 State and now we render
the component so now let's navigate to
this particular component and let's just
I guess set up heading two with some
kind of value as well as the button
because inside of the onclick we'll try
to change the state values so I think I
want to do that first and then we'll
worry about the actual logic so in here
inside of the div I want to go with
heading two I'll add one of the classes
so margin bottom is going to be set to
one and I guess I'm just going to leave
this one over
here then let me go with a button let me
remove this heading
to and let me add some classes just so
we have some basic styling so
BTN Center over here and then let's just
right click me and eventually we will
set up the on click let's not worry
about it right now this is what we
should see on the screen now I don't
know whether you remember but actually
we already covered sort of the Ed state
during the
fundamentals we talked about it when we
discussed the generics but let's go over
it one more time so yes we can nicely
use use state in react to control the
local state but if we take a look at use
State it's actually going to be a
generic so let's start I guess with the
import so looking for use State it's
coming from the react and let me just
hover over it notice this is going to be
the type definition it's a function it's
a generic and essentially we can either
pass in the initial state or we can pass
in the function and as far as the return
notice it Returns the value we provide
in the initial State and the function
that controls it so where I'm going with
this if we have just primitive values in
the use State you'll see that typescript
is very smart and it's going to infer
the type so for example if I'm going to
go over here with text and set text and
set it equal to my use State I don't
need to set up over here the type and
say that is going to be a string because
typ script is going to know that so if
I'm going to go here with shake and bake
and if I'll have our over text step
script knows that it's a string so
essentially whenever I will try to
update this value it's going to expect
the string and we can actually see that
over here if we go with on click and
let's not worry about how we can handle
events in react we'll cover that a
little bit later for now let's just pass
in our Arrow function just so we can
invoke set text and if I'm going to
provide a wrong type it's not going to
work so notice again as we're hovering
over what is the set State action
function looking for it's looking for
type string so it's going to be okay if
I go here with typescript yeah there are
no complaints but if I'm going to
provide the number immediately
typescript complaints again the logic
technically is going to work during
development I can navigate over here
press and technically I shouldn't have
any errors in a console nope everything
is fine but typescript is not happy with
me and the same is going to work if
let's say I'm going to set up the number
so let me navigate over here and instead
of text we're going to go with number
and set
number okay good and then we'll provide
the Primitive value over
here and you know what let me just
comment this one out for your reference
if we're going to go with set number
again we can see that set State action
function which essentially is a type for
this one for our set number function in
this case is expecting a number because
typescript is going to infer the type if
I'm going to provide it if I'm going to
say 23 yeah everything's awesome if I'm
going to go with some kind of string
value it's not going to work now it
doesn't stop me from explicitly going
over here and saying number I mean we
can still definitely do so but again the
whole point is that typescript is going
to do a very good job of inferring such
type now it's going to be a different
scenario if let's say we have empty
array as our initial value so let's say
we have over here a list then comma and
set list and we set it equal to use
State an empty array notice how
typescript essentially sets list to an
array but the type is equal to a never
and at this point we have few options
either we provide some values over here
so typescript knows what the type is
going to be so for example I can go with
hello but keep in mind there are
instances where you want the default
value to be empty array so I'm not going
to provide some random hello just to
make typescript happy so the solution in
this case is to use the generic approach
where we know that US state is in a
generic and we'll just say all right
yeah yeah it's an array but it's going
to be an array of strings and at that
point if I'm going to go to my on click
and go with my set list again my
function everything is going to be
awesome if I'm going to provide the
strings over here I'm going to go with
hello and maybe I'll also add over here
world so this is going to fly because I
have strings in my array however if
we're going to change this around and
we'll go with one and three notice
typescript is not happy because it's
expecting a type string so this is how
we can work with use State and
typescript by default typescript is
going to infer the type but it is a
generic and there's going to be
instances where we'll need to
explicitly provide the type that we
expect for the value and automatically
is going to be set for the set function
as well okay and up next let's cover an
example where we have a list of objects
now in my case I'm going to create nav
links but again the actual data is
totally up to you so I'm going to go
with naab links that will be my array
and I'm just going to provide some dummy
data and yes I will in the beginning
rely on the fact that typescript is
going to be able to infert a type so in
here I'm going to go with id1 then URL
I'll just type some URL so essentially
it's going to be some kind of string and
also text will be some kind of text so
some text okay let's save it then we
want to copy and paste so one and two
let's just change these values over here
two and three and I don't think think
I'm going to change any of the actual
values I don't think it's relevant now I
do want to set up the type type will be
equal to a link I'll say that ID is a
number okay awesome then URL will be a
string and then text will be a string as
well let me save it I'm not going to set
it up over here this is something we're
going to do later and now let's see how
we can work with that in our use state
so in here I'll call this links and set
links that will be my function name
we're going to go with use state for now
let's not set the type explicitly and
now let's just provide the nav links and
again typescript is super smart now it
knows that essentially links has this
shape and essentially we can go over
here where we have our own click we can
invoke set links let's say that I just
want to add it to an existing array so
I'm going to spread out all the current
links and I'm going to try to add a new
one if the values I provide don't match
the signature you'll see that typescript
will complain so if I'm going to go with
id4 then URL is going to be equal to
hello and then also a comma and I'm
going to go with I don't know what was
the last one I believe it was text right
if I'm going to say hello yeah
everything's awesome because this
matches the signature however if I'm
going to Omit text notice tapescript
immediately is going to complain because
the text property is missing so all of
this is nice the problem
becomes this is inferred and remember
when typescript infers something it
infers based on what on the original
value so for example if I just go and
comment this one out now notice
typescript thinks that yeah links
technically can be an array of objects
with this shape or with this shape where
text is actually missing so now if I'm
going to go here I'm actually going to
be successful so this is a good use case
where we want to go with our angle
brackets and we want to say
yeah we have these links over here but
actually the type is going to be
following it's going to be an array of
Link type so now typescript is going to
complain it's going to say Hey listen
you know whatever values you provided
they don't match so we need to fix it
over here and now the same deal is going
to be in our on click as well we'll have
to provide I believe it was our text one
now lastly I just want to mention that
technically we can avoid all of this
debacle pretty much if we just go with
our type annotation over here and we say
with the link then of course I'm not
going to be able to remove the property
but keep in mind there's going to be
some instances where you're not going to
be setting that data so again that's why
it's super useful to use the angle
brackets and to explicitly let
typescript know that the shape You're
Expecting is going to be following and
that way essentially later when you need
to update it's going to be very hard to
provide the wrong data and up next let's
see how we can handle events in react
for starters we want to change the
import so we're looking for
starter and the number four events one
the component is not expecting anything
because we just have the bare bone setup
with the div and all that and initially
I just want to set up two controlled
inputs one is going to be for text and
one will be for email and of course in
the process you'll see why we have two
of them so let's do that let's go with
use state that is coming from react
awesome then let's go with our text and
email and yes I will rely on the fact
that typescript can nicely infer the
Primitive types so I'm just going to go
with empty value
that will be my string and the same is
going to be for email let's provide the
name here and let's go with email let's
save this and now we want to set up two
inputs inside of the form again just for
better styling and all that I'll wrap
this into a section then we'll provide a
heading to I'll call this events
example and we want to go with our form
for now no action don't care about that
but we do want to add a class of form
and inside of it let's go with input
type will be equal to text let's just
add few classes here we're looking for
form input and margin bottom is going to
be set to
one since I'm creating over here a
controlled input I'm going to go with
value and on change so let me go with
value so that will be equal to my state
value so I'll set it equal to my text
and then also we have unchange which
essentially controls that value so we're
going to go over here with unchange in
here I'm going to pass in the arrow
function and remember we have access to
the event and now let's go with our set
text and let's pass in event. target.
value so again this is typical setup for
controlled inputs in react there's
nothing really
unique now we want to copy and paste and
we want to set up one for email the
difference we're not going to use the
arrow function we'll actually set up the
function reference so type yep still
equal to or you know what no it's
actually going to be email then the
class name for input yeah that stays the
same value will be email so this is
coming from the state and
also on change like I said there will be
a reference so you know what for now I
guess let's just remove it even though
most likely it's going to complain then
let's go with our button and Just for
kicks let's go with type and let's set
it equal to submit then let's add some
classes BTN and BTN block and let's
write over here
submit and actually this is something
that we covered previously when we
worked on the tasks application during
fundamentals you see in here when we
provide the arrow
function T script will nicely provide
the value for the
event as you can see it's react. change
event so that's the type we get from our
declaration files and it's a generic and
essentially we provide over here
the element the HTML input element and
this gives us a good clue what we need
to provide over here in the function
reference so if I'm going to navigate up
and I'm going to go with const and then
handle change function and if I'm going
to try to access the event typescript is
going to complain and it's going to say
Hey listen this is type any so for now
let's not worry about it let's just go
with event. target. Val just so you can
see that we can access that and let's
also go with our
set email and we want to provide the
same value so event. target.
value now let me navigate to my browser
so at the moment it's just complaining
because we haven't set the onchange this
is our form notice I can provide the
value but I cannot do the same for the
email and in order to provide the
correct type again we simply want to
reference what we have over here so
notice this change
event we want to go with event then
react Dot and then we're looking for the
change event and if we take a look at
the docs if we take a look at the type
definition we can see that change event
type is a
generic it's expecting a type which is
going to be the HTML element and the
default value is going to be element now
where we get back is Target and that
will be the intersection type between
the event Target and the type we provide
so now let's navigate back to our index
DSX and set up the angle brackets and
provide the correct element so we're
going to set this change event on H DML
and input element so now we have access
to the Target as well as the value so
this is what we need to do when we set
up the function as a reference again if
we just provide the inline
one everything is going to be set
already for us so now let me just
navigate over here and we're going to go
with on change and we'll set it equal to
anal change and with this in place that
typescript doesn't complain and also we
have the correct values in the browser
so let me go over here notice I'm able
to provide a value and the same is going
to be with my email okay and while we're
still on the topic of events let's cover
submit event and few things we need to
be aware of when we work with form data
API so let's say we want to handle the
form submissions we know that in react
there is onsubmit and same deal we can
either pass in the inline function or we
can set up the reference and just like
with on change event essentially if we
pass here the inline typescript will
right away infer the correct type if we
set up the function
reference then we'll need to do it
basically manually for
ourselves and you'll see that the form
event is very similar to change event
it's also going to be a generic and
we'll just need to provide the correct
HTML element and I think I'll right away
set up the function reference but you
know what before we do that let me just
mention that in between the videos I
added two
attributes one on each input and it was
the name attribute so in here I just set
the value for text and in here for email
simply because we will use the form data
in this video as well and in order to
access those values we need to add those
name attributes now I'm fully aware that
these are controlled inputs so
technically when we submit the form we
can access both of these values directly
but I do want to showcase some things
about form data and therefore I added
these attributes so if you want to
follow along I suggest you do the same
so like I said I'll right away set up
the reference let me go here with on
submit and I'm going to set it equal to
handle submit a function I don't have
yet so let me go with handle submit and
what is
typically the first thing we want to do
that's correct we want to prevent the
default so for now again I just pass in
the event and since typescript has no
idea what e I'm talking about it's going
to complain and it's going to say that
the parameter any so first let me just
set up the logic
prevent default and if we want to get
the type again we can always use the
editor as our best friend so notice
essentially we have over here the HTML
form element and then we're looking for
form event or you can pass in the inline
and you'll get the exact event type so
in here where we have the event we want
to go again with react or we just import
this type then we're looking for
form it's a generic and in here we
simply pass in HTML form and element and
now we have the correct type so now we
can use all the properties and methods
and typescript is going to be happy and
not going to complain now as far as form
data it's a nice interface to handle AE
if you have bunch of form inputs and you
don't want to deal with controlled input
so you don't want to set up the state
variables you don't want to set up the
on change as well as the value then it's
pretty straightforward just set up the
form add those name attributes and
you're good to go once you submit the
form you'll have access to it by
creating a a new instance of form data
so in here we want to go const form data
we want to set it equal to new
form data so this is right away
available to us we don't need to do
anything and then if you don't work with
typescript essentially we have two
options we can either go with
event. current Target and notice how
with
typescript we can do the same typescript
is not going to complain however
if we're going to go with event. Target
which again we can do without typescript
actually it's not going to work if we
use typescript so let me just comment
this one out for your reference and
actually I'll use this one later on
anyway but if we go here with
event.target
it's not going to fly so typescript is
going to complain now way around that is
to basically go with HTML and then
provide form element so we just add this
type assertion where
yeah we're looking for event. Target but
we say that Hey listen this is going to
be actually a forum element now if we go
with current Target typescript is smart
and it can see that we already have this
element over here so let me like I said
come in this one out and actually use
the current Target and then one more
gotch about form
data potentially the values could be
null as well and we need to handle that
so how does that look like well for
stars let me just showcase how we can
nicely access all of the values so if we
go here with object dot then from
entries so now we just need to provide
deform data and we'll get access to all
of the values so if I go with data then
let me refresh and provide some values
so some name and
email at
email.com let's see where we get back
once we click on submit notice we'll
have this object and even if we have 15
inputs we'll have a object with 15
properties with all of the values over
here and as far as the gacha well let me
first create a type just so we can
clearly see that so let's say we have
over here type person is equal equal to
and then name and that will be equal to
string so pretty straightforward type
and then let's go here with const
person let's set it equal to our person
type and we're going to go here with
name and now let's get the value now
it's going to be the same for the object
over here for the text property inside
of this object but first I'll just
showcase what happens if we use the form
data. getet method which is available to
us so let's say I only want to get the
text value I can always go here with
text equals to form data then dot get
then we need to provide the name and the
names need to match so let's say in this
case I want to access the
text notice the value that I'm getting
back either it's going to be form data
entry value type or it's going to be
null now why do we care about that well
if I'm I'm going to set my name equal to
a text typescript is not going to be
happy about that it says Hey listen
potentially it can also be a null and
you cannot
assign this value to a string so the way
around that is to again use the type
assertion where essentially we go with
as and then we set it equal to string
and here again I'm telling typescript
that I know more about the project where
yeah maybe this can be known but in this
case I know for sure that value is going
to be correct because I know that these
two values match and now notice how
everything works and the same is going
to be over here let's say if we go with
data. text remember that was the
property name again it's not going to
fly so in that case we again need to go
with as and then string and now
typescript doesn't complain so just to
recap whenever we set up events in react
if we provide the inline
function everything is inferred as far
as the event type so there's really not
that much difference between typescript
or not typescript however if we set up
functions as the
references then we'll need to provide
the correct type for the
event and there are two things things
that we're looking for we first need to
grab the correct event type and also
we'll need to
provide the correct HTML element since
most of these events are actually
generic now if we want to get the quick
suggestion we simply can set up the prop
on the element and then provide the
inline function and the moment we do
that we'll get a nice suggestion with
the correct event type and the correct
HTML element okay and up next let's work
on a small Challenge and I think it's
going to be
easier for me to
showcase the requirements so
first let's set up the import but in
this case we're looking for the final
folder so all this time we have been
importing from the Star this is the case
where we will import from the final one
so let's go with Port let's come up with
a name in my case it's going to be
component from then we're going to go in
the final one more specifically
Challenge and then we'll set up two
instances so first we're going to go
with component we'll need to provide the
type as far as the values notice we have
two options we can either go with
Advanced or basic so let's start with
basic
then if we have basic we'll also need to
provide the name in my case I'm going to
go with Susan let's close this component
and let's set up another instance where
we're going to go with component then
type now if we go with Advanced now
we'll need to provide more values not
only we'll need to provide the name
which is going to be Anna also we'll
need to provide the email and let's go
with Anna gmail.com and if we take a
look at the browser you'll see something
like this so so this is going to be the
look for the basic one and this is going
to be the look for I believe the name
was Advanced so here's the challenge
create a component that has following
features if we provide type basic we
only look for
name however if we provide type Advanced
we also need to provide email so for
example if I'll try to set up ADV
Advanced without the
email typescript is going to complain
and also based on a type notice how we
have different looks so for the basic
one we have this one and then for the
advanced one we have a different look
now a tiny hint as far as the classes in
here in CSS you're looking for alert and
alert danger and success so this CSS
part is totally
irrelevant technically you can skip it
for example you can just add a red text
or something along those lines for one
of the classes the general idea is to
create a component where based on that
type we are
first providing different sets of props
and if we don't then we get the error
and also we get a different look so try
to work on this Challenge and in the
upcoming videos I'll show you my
solution okay and first let me show you
a typical react solution prior to
typescript we'll also take a look at the
potential issues essentially we won't be
able to complete the challenge and in
the following video I'll show you a
proper typescript solution so first let
me comment some things
out first one the import and then these
two so I still want these for your
reference because they will help me to
showcase the potential issues and now
let me grab the import component from
and now we're looking for the starter
and same folder so we're looking for the
challenge and we want to render that
component somewhere so let's render the
component let's take a look at the
browser so now we have react and
typescript
Challenge and initially our approach
could look something like this where we
know that we need this type prop we also
know that we need name and email and we
know that based on that type we will
display one set of classes and if it's
the opposite then we'll display a
different set so let's navigate first to
starter and then index I guess we can
right away set up the type over here or
interface that is totally up to you I'm
going to go with type profile card props
three properties so we start here with
type
just because I enjoy it so much I'm just
going to go with the literal type so I'm
going to say yeah the possible values
here are basic or they're going to be
Advanced then there's going to be a name
which is a string and also we'll set up
the email which also will be a string
cool cool cool and awesome start then in
the component I'll say yeah there's a
prop subject and actually it's going to
have this type so profile card props
okay cool then let's gather all of these
things so we're looking for type name
and email and that is equal to our props
typescript is complaining because we're
not using these elements and you know
what before we set up the return let me
just set up the logic for the class so
essentially if the type is basic I want
to use the success one and if not I'm
going to use the danger again just to go
back notice in the index we have this
class for alert so this is just going to
add the padding and or radius and all
that and then based on this class so
either alert danger or alert success
we'll just have the background color and
color and yes of course we can set it up
over here in the return but I'll do it
above since in my opinion it's going to
be easier to see what we're doing so
alert type is going to be equal to type
then either basic or Advanced that is
totally up to you and I'm going to go
with success since that's the class name
and yes they do need to match and then
based on this one I'll set up my class
name so I'm going to go with const class
name and we'll set it equal to alert so
that's my main class and then alert iph
and now let's access the alert type so
hopefully it's clear that if it's going
to be equal to Advanced essentially not
basic then the value is going to be
danger if going to be equal to basic
then essentially the value will be
success and as a result our card is
going to look different so in here we
want to go with
article and then let's add a class name
so let's access our variable over here
or constant I guess more properly and
then let's just access both of the
props so the first heading two is going
to be user so we're going to go user is
equal to our name prop now when it comes
to email it's going to be a little bit
different simply because we only want to
display the email if the type is equal
to Advanced correct so in my case I will
only display the email if it's
provided now we can set up turn operator
or we can use the good old hand operator
and I think I'll stick with that one
because in my opinion in this case it
doesn't really make a difference so
let's look for heading two then let's
set it equal to email and now we just
want to access the email prop okay good
we have everything in place now let's
navigate back and let's provide these
values and you'll notice something
interesting we will only be able
to display the advanced component let me
showcase why so let me go here with type
we're looking for
advanced then let's go with name again
doesn't really matter what we provide so
I'm going to go with Susan and let me
also provide the email over here let me
go with Susan at
susan. let me save it everything looks
correct but notice if I'm going to go
here with the basic and just omit the
email not going to be successful why
well let's take a look at our type
typescript is expecting this email one
so if I'll copy and paste over here and
if I'll say yeah the type is going to be
basic and actually I don't want to
provide the
email typescript is going to complain
it's going to say Hey listen I still
need this email and technically you can
make an argument okay well I could
provide email over here and just provide
empty string and even though it kind of
works you have to agree that this is
somewhat
clunky
my goal is to have a component where if
I provide this type Advanced I am
looking for email and if it's actually
type basic I'm not even looking for this
prop that's my
goal now you could make an argument that
we can go back and make this one
optional over here and yeah technically
it works for the basic one right now but
what about the advanced one so now this
technically is optional as well so if I
remove it typescript doesn't complain
but if I navigate back I'm not showing
the email in my Advanced user card as
you can see in both of the cases we have
issues we don't have the
setup that we're looking for and
therefore in the following video we will
cover a proper typescript solution and
since I know that I'm going to get this
question a lot let me just answer it
here no adding following logic to our
component is not going to solve the
issue so yes
definitely not only we can check for
email we can also check for type and set
up the tary operator where if the type
is equal to advaned then we display the
heading to with an email and if not we
go with null but notice our component so
for example if I have the advanced one
yes it nicely requires the email and
once I provide everything is
awesome but it's going to be the same
thing with our basic one so since the
prop is present I need to provide it and
yes I can still provide the empty string
but remember that's not my solution
that's not what I'm looking for I don't
want to randomly provide these empty
strings and if we change this one around
to optional property same deal
now if I go to app DSX and remove both
of these values over here notice
essentially the first card is correct
but the second one has empty email value
so yes even though this one looks like a
better solution essentially it has the
same
issues as the one that we used before
where we checked for the email all right
and once we have covered the issues with
our initial setup
now let's complete the challenge
by constructing a proper typescript
solution for starters I do want to
remove these ones so I want to start
from the scratch and essentially in here
we want to create two types so our
component actually is going to have two
types so the first one is going to be
basic one and second one will be
Advanced so we're not going to use this
literal type over here we're actually
going to hardcode it equal to a basic
and since there's going to be two types
I'll also name this one basic profile
card props now let me copy this one and
in here we want to remove the
email and it's not going to be optional
anymore so if the type is Advanced if
we'll have this type then we'll look for
all of these properties so type is going
to be equal to Advanced name String and
email string now for the basic one we'll
only have type basic and name type is
going to be a string now where we have
the component I'll actually create
another type I'll say profile card props
and this will be a union type with basic
profile card props and the advanced
profile card
props and in here we're actually going
to set up to return based on a type so
for starters what two properties we can
always access well it's the type as well
as the name correct because keep in mind
we only have access to email if the type
is equal to Advanced profile card props
so therefore we're going to look for two
properties that are always going to be
there so name and type and now
essentially we want to set up our return
where we're going to go with well if
type is equal to basic one of the
potential values then we'll have one set
of elements if not well then we'll
return prey much the other card so let's
go here with the return we're looking
for the article so in this case we don't
need to set up that logic to add classes
based on type we simply we want to go
with class name alert alert
success and then inside of the article
we're just going to go with heading two
user and we'll access the
name so let's set it up over here and
then if the type is
Advanced basically our second option
you'll see that we have access to props
that email so let's go here with the
return and as a sign you can actually
structure it here as well so in here you
can go with email and actually
typescript is not going to complain and
it sees that email is actually a string
simply because if the type is basic okay
we have one return so it knows that at
this point the email has to be present
now in my case I will use the props that
email again doesn't really matter which
way you pick so we want to go over here
with article then let's add the classes
now we just want to provide the
different values so it's not going to be
success it's actually going to be a
danger one and then inside of the
article we're going to go with heading
two we're looking for user then we want
to access the name just like before and
we'll also add the heading two with
email and then we'll grab the props that
email so now let's navigate to app and
if everything is correct if we type
basic we only need to provide the name
and we'll get the correct look however
if we go with Advanced we'll need to
provide both of those values so if we go
with component type notice we have basic
or advanc so those are our two options
if we go with basic we only need to
provide the name so now we have property
name is missing okay good it's provided
and notice how we don't need to provide
an email here with an empty value no
that script is Happy everything's fine
we have correctly a basic user card now
if we're going to go here with component
type and we'll set up the advanced now
it's looking for name and email so one
by one let's set it up we have name
again let's go with our Anna and email
and let's just provide the value Yep
looks about right hopefully everyone
enjoyed the challenge and we can move on
to the next topic all right and up next
let's see how we can use typescript with
context API before we begin please keep
in mind that we will write bunch of the
boiler plate code meaning don't get
overwhelmed by the amount of code since
you'll be able to take it from Project
to project and second at this point in
time context API is not as popular
anymore so if you don't find these
examples useful don't stress about it in
fact if you don't use the context API at
all in your apps feel free to skip the
following videos for context API I did
prepare two examples the very basic one
with just one state value and a more
complex one with more bells and with
just so we can cover all the topics step
by step so let's start just like with
the previous examples where we want to
import from the star in this case we're
looking for the context one and in this
case we'll create two files so one is
going to be for context and essentially
in the index one we'll access the
context now if you work with context API
before you know that technically we can
wrap the app component in context we can
also set it up in the main
DSX so there's tons of options but in
this case I just decided to set up
everything in the context just so it's
easier add it to the final one and leave
it for your reference so don't be
surprised if in this example we'll have
two files so for stars we're looking for
component so this is coming from where
we're going to final and then we want to
look for context again let's render it
somewhere here on the screen the
component one and let's navigate to our
06 context one let's create a new one
and the name is going to be context DSX
in here we need two Imports and you know
what actually I'll set up the third one
as well since we'll use it in the
following example so we're looking for
two functions create context one and
also use context since we'll set up the
hook as well and then lastly in the
following example we'll use the use
state so I'll add that import here as
well right away and for now let's just
create a new context now as far as the
naming you'll notice that I keep using
this theme and it's simply because the
following example is going to be for the
theme and I prettyy much want to use the
same names so we'll just build on this
example that way we don't need to type
too much so theme
provider and let's call this context
let's invoke create context now this is
going to be generic and the difference
between normal react and react with
typescript is that we'll have to provide
the default value so in this case I'm
just going to go with undefined let's
imagine that we don't know what the
context is going to be then we want to
set up a component which is actually
going
to wrap all of our components and
provide the context so we're going to go
here with
theme provider and if you're familiar
with the context API you know that this
component normally is looking for
children so it's looking for the
component since it's a context provider
so in here we'll definitely need
children and we know already that as far
as the type we can either use the type
provided by react or we can just go with
react and then do and react node
somewhere here now as far as the logic
here's where we want to go with return
and we'll just set up one value so we're
looking for theme provider context it
has the provider component so we go here
with the provider and then we want to
wrap the children we'll go here with the
children and notice how typescript is
complaining because we do need to
provide the value now once we provide a
value you'll notice that typescript is
not going to be happy with create
context setup so for now let me just
showcase the basic example let's say I
provide over here the hello and the
moment we do that notice we right away
get the red squiggly line and the error
message says well you cannot assign
string to undefined so this was okay
initially when we were creating the
context we could say all right so it's
going to be undefined but now typescript
is complaining and in order to fix it
create context is a generic and in here
we'll use the type Union first we'll
provide what is the eventual value which
will be a string here and we'll also go
over here and say that it can be
undefined so this will be our initial
value and then this will be our eventual
value So eventually we'll have this
value equal to string and that's why we
have over here this type I'm purposely
keeping still this undefined because
it's going to be super useful once we
set up our custom hook so even before we
wrap any of our components I also want
to set up a hook called use theme again
I'm just going to keep these names since
we will use them in our following
example as well and in here we want to
invoke use context which is looking for
the theme provider context essentially
any context so let's set up this one
context is equal to use context and
we're going to go with theme provider
context and now if the context is
undefined I actually want to throw the
error now when the context is going to
to be undefined because at the moment we
can clearly see that actually we do have
a string well this context could be
undefined if let's say we're trying to
access this use theme but the component
where we're using the hook is not
wrapped in the theme provider context
and in my opinion it's a good setup
because that way we immediately can see
that there is an error and you'll see
what I'm talking about in a second if
this is confusing so I'm going to go
here with context and if it's actually
equal to Define I'm going to throw the
eror and if everything is correct then
we'll return the context so say here
return context but before that we'll go
throw new and error and let's just
provide some kind of error message my
case I'm going to go with use theme must
be used
within the theme provider let me save it
over here and now let's navigate to our
index one let's import both things the
hook as well as the theme provider and
now let's set up the parent component so
we're not going to export this one as
default actually there's going to be a
parent component where we'll have our
theme provider so first let's start here
with use theme okay yeah that's coming
from the context and I also want to grab
the theme provider and then let's set up
the parent comp component again this is
just to demonstrate how we can wrap
components please keep in mind that
typically you'll do that in the app or
in the main DSX so we go here with
parent
component that's our function basically
our component and as far as default one
I actually want to export the parent
component not the component and then in
here let's go with theme
provider and then inside of it we want
to place the component essentially this
one and once we nicely wrap the
component we can actually go over here
and I can go with context go with use
theme so that's my hook this is how I
can access the values and basically if
we log over here and provide the context
if everything is correct we should see
that value hello in the console so now
let's navigate to the browser and H this
looks
interesting so it looks like I'm
grabbing the file from the final one so
let me navigate back yeah we're not
looking for final my bad so we're
looking for the starter in this case and
once we do that notice the value is
hello and essentially it matches
whatever we pass over over here in the
value prop now of course normally this
is going to be more complex for example
you could have here an object and name
is going to be equal to something let's
go with hello same deal now I'll just
need to go back over here where we
create the context and just provide that
eventual value so again this is
undefined this is the default one and in
here I can say that yeah there's going
to be an object and the property is
actually going to be string so notice
now if we navigate to the console we'll
see this value instead and the reason
why this line of code is so useful is
because if we navigate back and for
example we forget to wrap everything in
our theme provider basically let's say
that we are trying to access our theme
context without wrapping the theme
provider and I'm just going to simulate
that by returning a component notice how
immediately I'm going to have the error
in a console and not only that it's
going to be super helpful where it's
going to say hey us te must be used
within the theme provider so this is
going to give me a super good clue what
is wrong with my current code and of
course now I just need to go back and
wrap everything nicely in the theme
provider so let me remove move this one
and now again we're good to go the main
deal over here when we use tapescript we
will need to provide what is the
eventual type for our value prop over
here and we can simply say that yeah
initially it's going to be undefined and
then
eventually whatever we set up in a value
we'll need to provide the type over here
and since the theme provider is always
going to be looking for children so is
going to be looking for components
therefore we'll need to provide a type
for a children prop as well all right
and now let's work on more complex
example please keep in mind that this
code is going to be available in the
readme just in case you ever want to
reference and also in the final one
you'll find this basic context and basic
index
TSX and essentially this is the code
that we set up in the previous video
because in my case I will modify my
existing code right now so for starters
I'm going to go here with type and theme
and I'm going to go with literal types
so we'll provide
light uh we'll also provide dark and
we're going to go with system and
essentially we're building here a theme
context provider so let's say in our
application we want to toggle between
the light and a dark theme and we want
to do it globally therefore we're going
to set up the context provider now let
me navigate to theme provider and
essentially I'll set up over here a use
state so I'm going to go with use State
and we know that it's a generic and I'll
say
yeah the value is going to be string but
actually it's going to be type of theme
and eventually we will provide the
default value let's not worry about it
right now and let's just go with
theme and as I not I do need to provide
the square brackets and we're looking
for theme and also a set
theme so we have these values over here
and as far as what I want to pass down
instead of this name hello I'll actually
go with theme and also a set theme so
now of course typescript is going to
complain because this doesn't match
whatever I have have here in the create
context so let's fix that let's set up a
type for our state which actually
matches whatever I have in the value so
we're going to go here with type theme
provider and let's say State props State
that's totally up to you I'm going to go
with theme and that is equal to a theme
over here so theme type and also a set
theme and essentially we'll just say
that that it's a function which is
looking for a theme and type will be
equal to a theme and it doesn't return
anything so we
simply provide void over here and
instead of hardcoding the object with
the name property which is a type string
we're going to go with theme provider
State now in this case it's complaining
because it says well theme can also be
undefined and we have multiple ways how
we can fix that either we can provide
the value like so so I can just say yeah
the default value is going to be dark
light or whatever
or in my scenario I'm actually going to
add one more property in the props and
therefore I will set up a separate type
so I'm going to go type theme
provider and let's call this props and
we'll look for two things first one is
going to be children so this one is the
same so react Dot and we're looking for
react node and also I want to set up the
default theme so let me add over here a
property default theme I will set it
optional and I'll actually set it equal
to type theme so it's going to be
optional but it needs to match one of
these values so light dark or system one
and where I have the theme provider I'll
actually remove the hardcoded one and
add theme provider props and in here
let's go with default theme and I will
add some default value which is actually
going to be a system and now at the very
end I'll go over here and provide
default theme and pretty much this
concludes our theme setup so as you can
see once we understand how we can set up
a basic context with just just one value
it's pretty easy to set up a more
complex one so now we just want to
navigate to index DSX and we want to
change our component around so this one
will stay the same and of course if you
want to test it out you can provide over
here the default value and all that
that's definitely an option but in my
case I just want to grab the context
with a theme and I also want to set up a
button which I'll use to change the
theme so in here right after this react
and typescript so I guess I'm going to
leave that I want to set up a button and
remember now in our context we have
multiple things not only we have theme
system but we also have this set theme
function so I want to try to invoke the
set theme on a button click just so I
can see whether my functionality works
so let's add over here a value I guess
I'm going to go with toggle theme and
then also let's add the onclick so we're
going to go over here with onclick let's
provide the arrow function and I'm just
going to check what is the value if the
value is equal to dark then I'll set it
back to system and if it's actually a
system one then I'm going to go with
theme dark so let's go here with context
Dot and we're looking for theme then we
want to check the value notice how we
right away get our nice suggestions I'm
going to say if it's equal to dark then
I want to set it to system context then
set theme and we provide the system one
then we return like so now if it's
already a system one then we just want
to go with context set theme and we
provide over here the value of dark and
you know what I also want to add some
classes here so let's go with BTN and BT
and Center let's save it now I have my
button and pretty much every time I'll
click on it I'll change this value now
we haven't set up any CSS so nothing is
going to change as far as the background
but notice as I'm clicking I'm actually
changing the value in a state so that's
how we can set up context API with
typescript okay and up next let's see
how we can use typescript with use
reducer hook and just like context yes
it's not as popular anymore since we
have options like Redux toolkit and Zoo
stand but you still might encounter it
from time to time and therefore I
decided to add it to the course just
like before we want to start in app DSX
hopefully this time I'm importing from
the correct folder so let me go with
star and now I want to go to Red
producers okay let's save it let's see
okay at the moment I have react and
typescript reducers looks about right
and this is the case where I do
suggest navigating to a readme and
basically we want to get some star code
because I really don't think that it's
going to be beneficial to type this
together so essentially go to 07
reducers and you're looking for this
function so this is what you want to set
up in your comp component not the app
DSX make sure you navigate to the
starter 07 and we're looking for the
index one this is what you want to paste
it over here and essentially this is
what you'll see in the browser so we'll
have increment decrement and reset so at
the moment nothing is happening we just
have some console logs over here and
also we have this set status to active
and inactive so basically our state is
going to consider consist of two things
so there's going to be some counter
value and also we'll change the string
value of active and inactive just to
Showcase how it works and our goal
essentially is to set up the US reducer
hook and also set up the reducer initial
State and all that cool stuff so now
let's navigate back to the component we
want to go with const and this is
returning two things State and also a
dispatch and we set it equal to use
reducer so we import that and it's going
to look for counter reducer so some kind
of reducer function and also initial
state so first let me just provide these
values please don't import them from the
final one we'll just go here with
counter reducer and initial state so
I'll set up both of these values now of
course we don't have them in this file
this is why we want to go to the folder
and we want to create a new one so in
this case I'm going to call this reducer
TS again if we have a component file yes
we go with DSX but if it's just going to
be a Javascript file then we just go
with TS so let's set up reducer yes and
let's start with the initial state so
this is something we're going to export
we're going to go with initial state in
a second we'll set up the type for now
let's just go with count which is equal
to to a zero and then status the initial
value will be pending but this is where
we'll change it to active and inactive
so now let's set up the type for this
one so export type counter State and in
here we have two values we have count
which is type number and also we have a
status which is equal to a string so now
we just want to go here where we have
the initial State and set up our type so
counter State okay awesome so we're
exporting that I guess we can now go
over here with import and we are looking
for our initial State and this is coming
from the same folder so we just look for
reducer so now we just need to set up
the counter reducer and for now it's
simply going to be a function and if you
know the reducer so it's looking for the
state as well as the action so what is
the state and what are we going to do
with that State and for now we're just
going to return that state so we're
going to go here with export then const
counter reducer so that will be the same
name and we'll set it equal to our
function our Arrow
function as far as the parameters this
is what we're looking for the state
which is actually equal to a counter
State and action and for now let's just
set it equal to any of course as we're
working on a functionality we're going
to fix that and and as far as what we
want to return from the function we're
going to go with counter State and then
inside we're going to go with a return
and state so pretty much for now we're
just going to grab the state and we'll
return State as it is so then back in
the index the
SX not only we have initial state but we
also have the counter
reducer so in the upcoming videos we can
start working on the functionality and
once we have setup in place I guess
let's start by displaying the value from
the state so at the moment we're
hardcoding the count as well as the
status but keep in mind that in here we
already have some initial values so
let's just access
those count is going to be equal to the
state that we're getting back and notice
how we have these two properties and in
this case I'm looking for the count and
the same is going to be for the active
one instead of Ive actually is going to
be equal to a state and then the status
let's save it notice now we have count
and also we have the pending one since
that's my default value and I think I'm
going to start with these ones so we
want to set up few types one for
increment decrement as well as the reset
one and we're going to start by setting
up a type and I'm going to call this
update count action so that will will be
my type over here so let's set it up so
type update count action and here I'm
going to go with the literal one so
either it's going to be increment
decrement or reset so type increment
then Union we also can have decrement
and also we can reset the value over
here and now I'm going to create another
type since there will be one for the
status one but technically I mean if I
would only have the count over here so
if I wouldn't have functionality to
change the status I can simply go to
update count action and set it equal to
my action so that will be my type but
since there's going to be more logic I'm
going to go with type and then
counter action and that one will be for
now equal to update count action so now
where we have the action in the counter
reducer we want to go with counter
action and now let's set up our logic
where inside of the counter reducer
instead of returning the state we're
going to go switch statement and we want
to go with action and type notice again
we have these potential three values and
then
based on the actual value we'll do some
logic over here so first let's set up
the default one and and let's say that
by default we'll just return a state we
say State over here and
then as far as the cases let's go with
increment first so that's going to be
our first case and then we want to go
with return and we want to pretty much
spread out the current state so we only
want to update and then count is going
to be equal to State DOT and count Plus
one and prettyy much we want to do the
same thing for rest of them so the
second one will be decrement case
decrement as you can see we only have
two options at the moment so decrement
and we just want to change this around
where instead of plus one we're going to
go with minus one and then lastly we
also have the reset case reset and if
that's the case just want to grab this
State and basically set the count equal
to zero now in order to invoke we need
to use the dispatch and we need to pass
in the correct type so instead of just
logging it over here we want to go
dispatch and then we need to provide
what is going to be the type and as far
as the increment one it's over here and
we want to repeat for decrement the same
same
dispatch type and then decrement and
then at the very end we also have the
recet one so as you can see the biggest
difference is that now we have a clear
control over the action type so usually
this was the biggest pain points where
you could provide some random value once
we use the typescript it's actually not
the case anymore we clearly have a list
of values that we can provide and we're
not going to provide anything random so
notice now I navigate over here to the
browser and I have these three working
buttons okay and let's also see how we
can handle the action where we have the
payload so with our counter pretty much
we're only handling the type correct and
then based on that we control the state
value but we can also pass in the
payload and for starters let's set up a
type for that so we're going to go with
set status and let's call this action as
well in here there's also going to be a
type so this property we definitely need
to
provide and as far as the value I'm
going to go with set status and then
when it comes to payload I'm just going
to go with few options and again I'm
going to use my literal type so I'm
going to go with
active and also it's going to be equal
to inactive then we want to navigate to
our reducer and let's set up the case
where we're going to go with set and
status and as I note before we do that
actually we need to add this set status
action to our counter action to our
counter action type because this is how
we're checking actually in the reducer
so let's go with set status action and
now notice how we're going to get some
nice suggestions so if I go over here
with case and then set status now we
just need to decide what are we going to
do and in my case I'm going to return
state so that doesn't change and as note
there is a error over here and now we
just need to update the I believe what
was
the value the status one correct so in
the state there is a status one and
we're just going to set it equal
to action and payload so we'll set it
equal to one of these strings over here
so now we want to navigate to index
DSX and where we have the console logs
to active and inactive same deal we just
want to dispatch it type going to be
equal to and we want to go with set
status and then we will need to provide
the payload as well so in here let's go
with payload and this will be equal to
active one I guess that's going to be
the first button and now we want to copy
and based and just change these values
around so instead of active we're going
to go with
inactive yep if I provide the correct
value everything is awesome so now let's
just navigate to the browser and not
only we can control the counter but we
can also change these values so we can
also pass the payload and at the very
end let's also not forget about the type
never so let me navigate back to the
reducer and we can see over here that by
default we return the state which
technically is okay but just keep in
mind we can add some kind of type over
here and this is going to fail silently
so for example if I'm going to add
another type over here I'm going to go
with something random if I'm going to
dispatch it I mean it's going to go
through my cases and essentially I'll
just get back to state so the problem
with this one is that it's very hard to
catch this error and therefore in here
where we have the default actually we
want to add some logic where I'm going
to go with con on handled action type
remember type is never and we're going
to set it equal to an action and now
notice how immediately it complains
because effectively there is another
type the moment actually it's random one
over here and unless we handle it so
unless I go over here case and then and
random and then decide what I want to do
for example return and then dot dot dot
State unless I do that there will be a
error and what's really cool that it's
actually at buil time so not at runtime
so now let me remove this example over
here and let's just complete by throwing
a error so let me go with throw new
error and let's provide some error
message and once we have this one in
place now we can remove it and not only
we'll be able to catch the error but
also if for some reason we add type and
we dispatch it there's going to be a
super helpful error in the console which
right away will lead back to the counter
reducer all right and up next let's see
how we can fetch data in react with
typescript and we'll actually look at
two options the good old use effect and
fetch API and my current favorite one
the react query with axio
please keep in mind that this section
will only make sense if you watch the
fetch data fundamentals part since I'm
not going to repeat things like Zod
setup and the actual need for types just
like in the previous examples we're
going to start in the app TSX where
we're looking for component and more
specifically the star and then 08 fetch
data and then if we take a look at the
browser this is what we should see we'll
also use the same URL like in
fundamentals so basically will fetch the
same doors from my server and therefore
I suggest just navigating to read me
you're looking for 08 fetch data and
just grab these two lines of code so
we'll utilize these hooks in a second
and then also here's the URL we're going
to use so grab it over here then we're
going to navigate back and I guess let's
just start setting up the state values
now eventually we'll set up the tors
but at the end of this video I'll show
you why we're not doing that right now
why essentially we need a type first and
then let's set up two more State values
we're going to have one for is
loading and then also set is loading so
this is going to be true while we're
fetching we're going to go with use
State and we can provide angle brackets
here it's definitely an option or we can
just type over here the default value
and then typescript is going to be super
smart and it's going to figure out that
essentially this will be a Boolean so I
guess let's just go with that one and as
far as my default value it will be set
equal to false then we also want to go
with is error and we're going to set it
to set is
error so that will be our set function
and here we're going to provide the
angle brackets and there's going to be a
union type so either it's going to be a
string so if there's error I'm actually
going to use the error message or or it
will be null and null will be my default
value so I'll just provide null over
here then the good old use effect and we
want to set up the fetch function inside
of it so let's go with our use effect
let's provide the Callback function
we're just going to invoke it when the
component mounts and inside of it let's
set up our fetch data which will be my
the same function so fetch data and
let's set it equal to a
sync and as far as the functionality
since it's a sync we want to nicely wrap
everything in the try and catch and also
we want to start by setting is loading
is true so while we're fetching we'll
set it equal to true and then at the end
we'll set it essentially equal to false
and you know what actually in here let's
go with finally so here we'll just set
it set is loading and equal to false so
whether we're getting the error or we're
successful doesn't really matter at the
end of the day we'll always set it back
to false now in the tri block this is
where we want to construct our fetch
which again we can right away start
using because we have access to it so
we're going to go here with await fetch
then we provide the URL then fetch API
has that Quirk where effectively we do
want to catch the 404 errors as well so
I'm just going to check for that okay
properly so if I have some kind of error
I actually want to throw it over here so
throw new error which of course will
right away lead to a catch block and
then as far as the message I'm just
going to say failed to fetch doers and
after this condition I want to set up my
raw data since eventually we'll set up
Zod as well and for now let's just go to
response.
Json and then let's log this data so
we're not going to set anything in the
state and when it comes to a catch let's
again construct that message so we're
going to go with message and this one is
equal to error and we're going to check
whether error is the instance off and
error and if that's the case then we're
going to go with error and
message or there was an error so
something generic and we also want to go
here with set is eror and we want to
provide our message so that should do it
we just want to invoke it over here and
we want to set up three returns so at
the moment we have one so basically this
is our standard return and now let's
check for loading let's check for is
error and then let's see whether we
actually are getting data and then we'll
discuss why we want to set up the tours
in the following video so let's start
over here we're going to go with if and
then is loading okay good and then we're
going to go with heading three loading
and then d da D okay good then we also
want to do the same thing pretty much
for
error so now we're checking for this
value and we're going to go with error
and actually we can display the message
as well just in case there is any so I'm
going to go with error and let's access
the error
message is error and then I'll just
leave this one for now So eventually
we'll iterate over that doors so now let
me navigate to the browser again if
everything is correct we should see
those doors and I can see the array of
Five Doors so that works should also
have that loading for a split second and
let's say if we're going to mess with
the URL if I'm going
to provide the wrong URL notice now I
have actually error failed to fetch T
and now again let's reiterate why do we
need a type so let's try to set up do
state value at the moment we don't have
the type so essentially we'll just
provide Mt then let's try to set it over
here in the fetch data and then let's
iterate over and see where the issue is
going to be so for STS we want to go
over here with const tours set tours
okay beautiful then we want to go with
use State and remember if we're just
going to provide over here Mt aray which
will be default value notice now T is
actually set equal to never which means
that yeah I can go over here and I can
go with set tours I can provide broad a
okay beautiful everything is awesome and
then let's say right after the react
typescript we're going to go with doors
then map so we're iterating over and
then as far as the function well let's
access the tour correct okay good and
then we're going to go with some kind of
heading two we provide hello we can even
see those hellos in the browser okay
beautiful but what if we're going to try
something like this let's say I want to
access one of the properties I'm going
to go with the name one so now if we go
here and say tour and that name this is
not going going to fly typescript is
going to say well you cannot access the
name property on type never and this is
why we do again need to set up D type
and in our case since we already know
how to work with Zod and since we're
going to use Zod
to evaluate our data at run time anyway
this is going to be our approach okay so
now let's set up our type and we'll do
that with the help of Zod Library since
that way we can also check the data at
runtime and this is totally up to you
you can set up the file name utls or
something along those lines I think in
my case I'm just going to go with types
now as a side note also in this file we
will set up a fetch
function with the axio so that is coming
up so basically we'll just Jam bunch of
the things normally in the bigger
project you would separate them but I
don't think there is any need so we're
looking for Zod Library which again is
already installed if you're using the
star if not then just please install the
library then let's construct that door
schema which will also then infer to be
our door so let's export that since we
also want to use that one in the inex so
we'll go with export then con store and
then we're looking for schema over here
so this one will be equal to Z do object
so this is what we're
constructing and I believe I had five
properties in there so all of them were
string that's for sure so we're going to
go over here then let's copy and paste
and I believe it's one too many by the
way so let me remove this one and then
we have one for name also we want to set
up over here image then same deal info
and at the very end we'll have the price
one I'm missing comma
so let me do that as well and now let's
construct our type this is something
also we're going to export so let's go
here with export type and then tour and
that is equal to Z infer so now we just
infer a type which is a generic and
we're just going to go type off and then
to our schema so now we have both we
have our schema and we also have our
type so now let's navigate back over
here and we want to import both of those
things we want to grab the tour as well
as the tour
schema so let me set her up I think I'm
going to type over here type tour just
to make it more explicit what we're
doing so we want to grab the scheme as
well and then this one is coming from
the types let's save this and now let's
just start using the type and I guess
right away also the tour schema so here
where I have the hug state for tours I
actually want to go with tour and the
array so essentially I'm telling
typescript that yeah this is an array
but eventually it will be an array off
TOS then we're going to keep on moving
and where we have the raw data same deal
I'm going to go a tour and I'll set it
as an array then we actually want to run
right now our tour schema remember there
is an array method and again I want to
save pars it so essentially I want to
throw the a myself and it's going to be
nicely caught over here so for now I
think I can remove both of these ones
over here we won't use them and
essentially we want to get that result
so let's go to the result then T schema
array let's invoke this and then we're
going to go save bars and and we're
looking for raw data and then as far as
the result remember we're checking for
the success
property and essentially if the data is
not present then we're just going to
throw the error so we're going to go if
and
result
success that's not the case then I mean
you know what I can actually log it so
let's go the
result error and message over here and
also we want to throw our own error so
let's go throw new error and again let's
do the same thing we'll go with failed
to
parse and tours and then at the very
very end we want to go here with set
tours and we want to pass in result.
data so if we're successful if we bypass
this condition pretty much we're good to
go and I think at this point essentially
we can just navigate to to our return
and we can just set up the proper return
so in here let's go with the heading two
I'm going to add some class so I'm going
to go with margin bottom and set it
equal to one then we're going to go here
with doors okay and then let's iterate
over so we have tours over here we want
to call the map and now once I type the
tour it will nicely be my object
everything starting with ID all the way
to a price and again this is something
that doesn't stop to amaze me so we're
going to go over here with return then
we want to set up the paragraph again
we're not going to really work on
Amazing result in the browser for now we
just want to grab the T ID we want to
add some classes over here so class name
and let's go with another margin bottom
one and then let's access the door Dot
and we're looking for the name and again
if everything is correct this is what we
should see in the browser yep everything
is awesome and if we go over here to the
types and let's say I'm going to add a
property I'm going to say that I'm
looking for something and that will be a
string and let's invoke that check it
out first I have over here a error
message in the console and we can also
see that over here now million doll
question do you always need to add Zod
when you're fetching data and to tell
honestly most likely that's not
something that you're going to see that
often for the most part you're just
going to rely on the fact that yeah the
API is supposed to return some kind of
type but it does come in handy when you
definitely definitely want to check for
that particular value so this is how we
can essentially Fetch with react and
typescript with the good old use effect
and fetch API and now let's see how we
can accomplish the same thing with less
lines of code and essentially no
headache and we're going to do that with
the help of axios and react query and if
you're not familiar with either of these
libraries please utilize the library
docs or some other online resource since
our main focus is going to be on
typescript and I actually want to start
by constructing fetch tours with
axios again normally you would set this
up in a separate file but in this case
I'm just going to do it right here in
the types where I want to install or you
know what actually it's already
available in the starter we simply want
to import the axios from axio library
which is an awesome HTTP library and
effectively we want to construct right
now the fetch doors and you know what I
also so I'm going to grab right away
this URL and I'll actually remove it
from the file since we'll set up use
Query over here as a side note as always
you can find
the code from previous lessons in the
read me so let me go over here this is
going to be my URL and essentially we
want to go with export const fetch doors
it will be a sync and as far as what
we're returning since it's a sync
function we want to go with promise and
then we'll set up our tour array and
then when it comes to functionality we
want to use axos and we want to stick a
weight in front of it so let's go with
const
response and that is equal to a
wait then axos doget remember this is
actually a generic and therefore in here
we pass in door and array so an array of
doors and effectively in this response
inside of the data property we'll get
back our array but it will be nicely
already set as type array off doors
hopefully that is clear and we actually
did cover that during the tutorial part
now let me double check over here it
looks like I have a syntax bug yep now
everything's correct so we have response
beautiful
then we'll do the same thing like in the
previous video where essentially I just
want to check using Zod and since it's
pretty much the same code let me again
just take it out and set it up over here
so we still use the result to or schema
in this case we're not passing a raw
data we actually go with response. data
again that's where the array is going to
be located and then from this function
we want to return
and we're looking for result. data so
since we have multiple libraries yes
we're pretty much passing this array
from one to another so first we use
axios and again just to demonstrate that
basically if we go over here with type
definition you'll notice somewhere here
get see over here it's a generic and
essentially it has this axio response
and then if you take a look at the xos
response one
notice this data it's a generic type
correct so whatever we pass in this is
what we're going to get back and once we
have this function in place now let's
navigate I guess actually to the main
DSX because we want to wrap everything
in the query client provider so we want
to install react query Library you can
also install Dev tools they have as some
Dev tools but in this case we're not
going to do that and in here we want
import the query client as well as query
client provider first we want to set up
a new
instance like
so and as a sign not something I want to
mention react query is actually very
good at inferring the types so as far as
types is concerned we actually don't
need to do much as long as we set up a
proper return type here in the function
basically what we are returning pretty
much we're good to go
so in here we want to go with new query
client let's invoke this and then we
want to wrap our app inside of the
render so let me set up my query client
provider we're looking for client that's
the prop and we'll set it equal to a
query client then let's wrap the app and
now let's navigate to index DSX and like
I said I'll pretty much start everything
from scratch and if you want
the code from the previous lesson please
just utilize the read me in here we're
looking for fetch dos a function we just
set up it's actually located in the
types okay and we also want to grab this
hook which we get from react query
called EU query again this is coming
from and in this case we have this stand
stack and react query so we have both of
these Imports now let's set up our our
component and let's also set up the
export since I know that I'm going to
forget to do that let's export the
component as default and for starters
let's invoke use Query so we're going to
get bunch of the things back and we want
to set it equal to use Query so notice
we don't need to set up our loading
error or any of that stuff and I'm not
even talking about the use effect
essentially we just invoke the use Query
and and we're good to go it's looking
for two things it's looking for a query
key since we'll nicely be able to
invalidate those queries later something
we're not going to do but just telling
you it is an option so essentially you
just provide some kind of string over
here so now this
query we will reference with the name of
doors just in case we ever want to do
something with the query like for
example invalidate and also we want to
set up a query function now this query
function has one rule and one rule only
it needs to return a promise that's it
that's all we need to do now if we
navigate to types what is this function
doing it's a sync what does that return
it returns a promise and like I said
react quer is awesome at inferring the
type so if we set up properly over here
that I'm going to be returning an array
of Tours react query is going to figure
that out so in here since I'm not not
passing anything in Fetch dos any kind
of argument I simply can set up the
reference now what are we getting back
over here we get back is pending so this
is while we're loading we get back is
error if there is any we also get the
actual error object just in case we want
to get the message and just like axios
in here we have this data one and inside
of that data we'll have that array of
Tours now since I want to use pretty
much the same name I'm just going to
give it an alas of Tours okay good and
with this in place now let's set up our
return so one by one uh first we're
going to go with is spending so check
that one if that's the case again same
deal we're going to go with heading two
or heading three and we'll go with
loading then we're going to go with is
error so if we have the error actually I
do want to
access the error message so let's go
here with error and we'll set it equal
to error object and in there we have a
message property and now let's iterate
over the tours and same deal essentially
we just want to showcase the tour name
in some kind of paragraph so let me set
up the return we're looking for div
inside of the div we're going to go with
heading two let's add a class name
margin bottom set it equal to one that
will be equal to
tours and then we want to iterate over
so let's call
map then each and every tour okay good
and then we want to return from the
function and I'm going to go with my
paragraph let's add a class name of
margin bottom one and also let's add a
key and we'll set it equal to tour and
then ID and then inside of it let's
render the door. name and if everything
is correct again the result is going to
be the same but like I said way less
headache way less State
values and pretty much everything is
already inferred so we only need to set
up a use Query we only need to set up
fetch doors and pretty much we're good
to go okay and now let's cover Redux
toolkit setup which is a good option if
you have a global State as side note if
you're not a fan of Redux
toit a Nifty alternative is Library
called zustand I believe that's how it's
pronounced which offers pretty much the
same functionality but with less
overhand and the code is also less
clunky I have to admit but since at
least at this point in time you will
encounter Redux to K it more often I
settled on rtk as far as typescript
Redux toolkit just like react query also
nicely infers bunch of the things so
it's actually less work than for example
use reducer but I'm not going to lie the
setup so the initial setup to add Redux
toolkit to our application with
typescript is somewhat of a pain now the
good news it's a boilerplate setup so we
can take it from Project to project so
most likely you'll only need to write it
once and in fact we will do a setup in
the following video so for now we'll
just prepare everything we'll actually
create our first slice and then in the
following video we'll complete the
boiler plate setup for Nots we want to
go to app DSX we're looking for starter
rtk the component if everything is
correct this is what we should see on
the screen and since we're shooting for
the same functionality as in use reducer
I suggest navigating to read me and just
grab this code so again this is just
going to set up some buttons
which we will use later to control our
state values so grab
everything in here as far as the
component is concerned you want to
navigate back over
here paste it and again you should have
five buttons and pretty much every time
you click on a button there's going to
be some kind of console log and then we
want to set up a slice now slice in
Redux tokit essentially is just a piece
of functionality so let's say in your
application you're handling the user so
the log out login whatever all kinds of
things well you'll set that one up in a
slice let's say you have a theme you'll
create a slice for that and hopefully
you see where I'm going with this now in
our case we'll just dump everything in
one so I'll say cter slice and we're
looking for TS since we're not creating
a react component then we want to import
two things so create slice is going to
create that slice for us it's a function
coming from Redux toolkit and second one
will be payload action which actually is
a type and this is something we're going
to use towards the end of the video so
now let's go with create and Slash
okay that's what we want to import over
here good then let's also grab that
payload but this is actually a type so
payload action and yep it's coming from
Redux toket beautiful now we will set up
some types in a second let's start by
creating that
slice so counter
slice and this will be equal to create
slice and second will provide some
values before I forget I do right away
want to export and actually we export
the reducer function so we go here with
default counter slice and then dot
reducer so this is something we're going
to use when we set up the store so think
of store as pretty much your entire
State and then the slice well this will
be that one functionality again in our
case pretty much that will be the only
functionality but in bigger applications
this is where you'll set this one thing
and as far as the crate slice it's
looking for a few things it needs to
have the initial State and we'll also
right away set up those reducers so you
know what let's just start setting
everything up if you remember when it
comes to the state we have count and
Status over there and then it will be
our initial State and this is something
that we're going to provide over here
here in the create slice so let's start
here const
initial state for now I'm not going to
set the type I'm just going to say that
count is equal to zero and then status
will be pending and remember we'll just
control it from active to inactive I
believe then inside of the create slice
we want to come up with the name and
essentially I'm going to call this
counter and then also we want to go with
our initial state in a second we'll set
up the reducers which control it but
before we do that well why don't we just
knock out those types over here so first
let's set up a type for the counter
state so type counter and state and in
here count will be equal to a number and
then when it comes to status I'll
actually set up the literal type because
we'll use it later to provide a proper
type to payload action so we might as
well set it up separately so let's set
up a status but instead of setting up as
a string I'll actually create another
type I'll call this counter status so
this is essentially something we control
when we add that payload over here now
when it comes to a counter we'll press
these buttons over here without the
payload and as far as the literal values
well we're going to go over here with
active
inactive and let's also add the bending
one and once I have this one in place
status actually is going to be equal to
a counter status so now where I have the
initial state I'm going to go with my
counter State and then we want to set up
those reducers so reducers are going to
be functions which essentially control D
State and then in order to invoke those
functions we'll need to display patch
them and again remember when it comes to
actual count the number the only thing
we need is whether we want to increase
decrease or reset but when it comes to
set status this is where we actually
pass in the payload now the good news
with Redux toit effectively if we're
just controlling this one value we don't
even need to provide D type and you'll
see what I'm talking about in a second
so we want to go with reducers it's an
object and then one by one let's up and
pretty much I just come up with a
function name so for example in this
case increment I right away have access
to a state and as side not yes redex to
it nicely inverse all of the values that
we need over here and then yes we can
essentially just overwrite so I can just
go with count plus and equals to one so
notice I don't need to provide my type
since I'm not providing any payload
that's it I only want to set up this
function over here and we will export it
in a second and eventually we will
dispatch it hopefully that is clear then
we want to go with uh decrement I
guess let's go with State same
deal we want to go with State count and
in this case we'll subtract and then
when it comes to
reset we just want to access the state
okay good and then set the state count
equals to zero as then note if you're
wondering why we can just modify the
state like that why don't we need to
return state from this function it's
because under the hood essentially Redux
is using a library which does that for
us so that's why we can actually kind of
modify the state directly in here under
the hood yeah we're still getting the
latest value don't worry and then we
have the St status which essentially is
going to have two things not
only we'll need access to a state but
this is the case where we will provide
eay load so effectively when we dispatch
set status we will provide that string
value and the string value is actually
one of these ones so either active
inactive or it's going to be pending and
when we use a Redux stol kit we do have
this special type which we need to use
so it's called payload and for some
reason not using so payload action not
sure why I'm not able to access that so
payload
action and it is a generic over
here and then inside of the generic we
want to pass in our own type so
basically we need to provide over here
this counter State now I do have over
here a syntax error and now as you can
see everything works so if you have the
action yes you'll need to provide this
payload action which again is a generic
and then in here you'll provide the type
so in this case it's somewhat
straightforward we just have a string
but keep in mind yes if you have let's
say an object with a bunch of properties
you'll have to set up the type and
provide it over here so typescript knows
what do you want to do essentially when
you pass in that payload and same deal
we want to go with state. status and
that will be equal to action payload
since that's where we have the string
now it looks like I have a bug my
apologies by mistake I provided the
counter state it should be
counter status my apologies now
everything's correct I don't have any
bugs and also we want to export the
increment decrement all the way to set
status so we won't need to provide in
our component let's say a type when we
dispatch we simply can pass in our
action and we'll be good to go so we go
here with export const and then we
should have access to all of our
functions so increment decrement reset
and then set status and that one will be
equal to counter slice and then we're
looking for actions this should do it
for the slice setup and in the following
video we'll do that somewhat annoying
boiler plate setup where we'll add the
Redux tokit to our application okay and
now let's take a look at that
boilerplate setup where effectively we
want to create two files we want to
create store DS as well as the Haw DS
and as a side not if you're using the
starter you should have already those
files now there shouldn't be any code in
them but you should have the files and
store is where we set up all our slices
so we create that Global store and hooks
is a special one because we're using
typescript and you'll see what we need
to do over there in a second so first
let's start with the store we want to
import configure store this is coming
from Redux tokit and also we want to
grab counter
reducer now this one is coming from our
slice the counter slice and I need to
make sure that it's coming from the
start so let me go over here with the
reducer from and let me look for
star then the rtk and then I want to get
the counter slice let me just double
check yep I'm exporting so everything is
correct and then back in a store we want
to invoke configure store so we want to
go here with export con store since
we'll wrap our entire application in the
store and inside of this function we
have a reducer property and essentially
this is where we set up our slices so in
our case again we have only one so I'm
going to go with counter is equal to
counter reducer since we're using
typescript we need to set up two more
types so export type and again in the
docs they use this root State they set
it equal to return type and inside of
this one they go type off and then store
and get state so this is what they pass
into this generic and the second type
when you want to set up over here is
export type app and dis
patch and this one will be equal to type
off and store this patch so once we have
these two types in place we want to
navigate to The Hook one and essentially
we want to grab use dispatch and use
selector so those are the two hooks we
use with Redux toit one is to access the
store and second one is to dispatch an
action
and we want to create our own and you'll
see what that entails in a second so
let's first grab use this patch again
this is coming from react Redux so this
is what I was talking about the annoying
boiler plate setup but again you only
need to realistically do it once so then
import this is actually a type and we're
looking for typed
use selector hook so this is coming from
react Redux and also we want to grab
that root State and app dispatch the
types we just set up so let's go here
with root and state somewhere yep that's
the one and I also want to grab the
dispatch okay we have both of these so
now let's set up both of those hooks so
we're looking for export const
use and the name is totally up to you
just make sure that it starts with use
that's just a rule for react talks and
in this case we'll actually go with the
function and we're going to go with app
dispatch and we'll set it equal to use
dispatch so it's going to suggest this
use app dispatch that's not what you
want to use you want to go with use
dispatch which is actually the second
one and then let's also set up the use
app selector which also we're going to
export so we go here with use
app selector and in this case we just go
with type selector hook we provide the
root
state or type that we have in a store
and we'll set it equal to use selector
here let's save it and now the last step
is going to be in the main DSX where we
want to import the entire
store from store file and and we want to
wrap it in the provider component which
is coming from react Redux library now
this provider component is looking for
store prop and as far as the value we'll
pass in our store so let's go here with
provider then
store set it equal to our
store then let's wrap it and with this
in place we have successfully added redu
toit to our application and in following
video we'll complete the functionality
okay so now let's navigate to 09 rtk
index DSX and we want to import few
things first we'll grab those hooks so
instead of use dispatch and use selector
we're going to go with use app selector
use app selector and we also want to
grab use app dispatch and then also
let's grab those actions from our slice
so I'm talking about decrement increment
reset and set status so let's grab also
this one this is coming from the counter
slice good then we have increment then
we have
reset and then we also have set status
all of that is coming from the counter
slice now in order to access the state
values we want to go with the use app
selector so that's the hook and
essentially by default it right away has
access to the entire state so I'm
talking about this one over here more
specifically we're looking for the
counter so we're going to go over here
and we're going to say State and as I
not I do need to pass here function and
then from the state we want to access
the counter so this will be our tiny
slice for the counter and we can nicely
right away the structure two things what
do we have in a state we have the count
as as well as the status so those are
the two things that I want to access so
now where I have the count I'll actually
change it around and I'll set it equal
to count and as far as the
status same deal over here now just to
keep it more interesting I'll actually
navigate back to my counter slice and
let's say set up my initial value to be
equal to 15 so now I can clearly see
that I have access to the counter as
well as my status one so now we just
want to navigate back and we also want
to invoke the use app dispatch which is
going to return a dispatch function we
can invoke so let's go here with cons
dispatch set it equal to use app
dispatch and then where we increment
decrement and reset we'll just invoke
these functions and then when it comes
to set status remember we also need to
pass in the payload so it's going to be
a little bit more code so we want to go
here with this patch and we just want to
invoke the increment same deal is going
to be for decrement and
reset so I'm pretty sure I can just copy
and paste so we're looking for decrement
over here and then lastly we have one
for reset as well so let me override
this one that should do it notice now
we're actually changing the count value
and when it comes to set
status it's pretty much the same we just
want to actually pass in the string
value whether that's active inactive or
pending so let's go here with dispatch
set status and again we'll get a nice
suggestion so these are the values that
we can pass in so it's kind of hard to
mess up so let me copy this set it up
over here and instead of active we're
going to pass in inactive so now let me
navigate quickly to browser and it looks
like everything is working as expected
and with this in place we have
successfully added Redux toolkit to our
application all right and up next let's
build a small tasks application before
we start coding away let me just mention
that if you enjoy the challenge and want
to build this project independently in
the readme you will find a list of steps
to build such app so if this is
something you're interested in pause the
video complete the steps independently
and resume once you're ready to compare
the results as far as the app it's
actually very similar to the app we
already built at the end of the
fundamental
section essentially we will create a
form and a list of tasks and if the user
provides a valid input we'll add a task
to the list and with the help of the
checkbox user will be able to toggle
whether the task is completed or not now
we'll start just like the other examples
where we want to navigate to app DSX and
we want to grab our components so in
this case we're looking
for folder number 10 I believe right so
we're looking
for
starter then forward slash and
tasks so let me replace whatever I have
in
here let me set up the component yep I
have task list so that is good and just
like before since we're working with
typescript one of the first things we'll
do is to set up a type and since we'll
use this type in multiple files it
definitely makes sense to set up types
yes and in this case there's going to be
only one type which will be a task so we
want to go with export type task and in
here we have three properties ID which
will be actually a string then a
description which will also be a string
and then is completed which will be a
Boolean let's set it up and then we want
to create two more components which will
render in the index DSX so so we have a
form component we set it up and also
there's going to be a list one new file
and we're looking for a list and then we
want to create our component and with
this in place now we want to navigate
back to index and we want to import use
effect use State as well as form and
list and also the type so one by one
let's set it up so use State then let's
also grab use effect and then let's grab
the form
one list
one and at the very end let's also grab
that type so import explicitly I'm going
to type task and then this is coming
from the types now inside of this
component essentially we want to start
by setting up the state value so in here
let's go with tasks set t tasks and this
one will be equal to use State let's
invoke this one and by default it's
going to be an empty array but we do
want to provide the generic over here
and we'll say that it's going to be an
array of tasks and when it comes to our
return I think I'm going to replace the
div with a section and in here let's
type the form component first and we
also want to display the list let's save
it over here now for some reason I don't
see anything looks like there's a bug so
it complains that Forum doesn't provide
the
import this is strange oh yeah probably
because I didn't save it my bad let me
try one more time if everything is
correct this is what we should see in a
browser and with this impl now we can
start working on the form functionality
okay and when it comes to form
essentially we want to set up the form
element inside of it there's going to be
an input and it's going to be a
controlled input so there will be a
state value as well and once we submit
the form we want to prevent the default
we want to check whether there is a
value provided in the input if not then
we will trigger the alert and if
everything is correct We'll add task to
the list something that's coming up and
also we'll set text back to empty value
I guess I'm going to start by setting up
two Imports over here so we're looking
for use State and also we want to grab
that type because eventually we will use
it not for now but let's go with type
and task which is coming from our types
and then let's start I guess by setting
up that state value so we have text and
set text and that one is equal to use
State and we want to start with empty
string eventually we'll set up the
handle submit for now I just want to
work on the return so we're going to
return a form element We'll add some
classes just so it looks a bit more
representable and we're going to go with
task form so again on submit is coming
up let's not worry about it right now
inside of the form we want to go with
input type will be equal to a text class
name is going to be form input
and also we want to set up the value
since this will be a controlled input
and let's also set up the
onchange I'm going to provide the inline
function since I don't want to bother
with the event type and we're just going
to go with set text and we'll go with
event. Target and value okay good and
then we also want to set up the submit
button so button then type is equal to
submit and class name will be equal to a
button and we're going to go with add
task let's save it this is what we
should see in the browser so now let's
just navigate back and set up that and
I'll submit so first let me I guess set
up the function this is going to be
essentially a repetition pretty much for
stuff that we already covered during
tutorial so we're going to go here with
handle submit remember we do want to
access the event but we do need to
provide the type ourselves in this case
so we're going to go with form event and
we're looking for HTML and form element
this is what we want to pass in and as
far as the
functionality first we're going to
prevent a
default so prevent default let's invoke
that then we'll check for text so if no
text provided then we'll go with alert
and let's just go with please enter a
task then we're going to return so we're
not going to do anything and if
everything is correct basically if we
bypass this condition then we're going
to go with that task and we'll go with
set text and we'll set it equal to an
empty string so now let's just look for
the form we're looking for
onsubmit and we'll set it equal to andle
submit so let's see let's see let's see
I think we can just log so instead of
adding the task for now let's just see
what is the text value whether we are
successful let me type some nonsense
here and looks like everything's correct
so I get the value in the console and I
also end up with an empty input now if
I'll try to submit without providing any
value then we'll get back the alert and
with this in place now we can start
working on the add task functionality
all right and up next let's set up
functionality to add task to the list
now we can take multiple approaches
essentially we can pass down set tasks
to a form and let's say if the value is
provided we can invoke set tasks it's
definitely an option but in my case it's
just a preference to set up everything
in the parent component and therefore I
will create another function and I'll
call this add task now this function is
looking for one thing and one thing only
which is a task but remember we have a
specific type for that so we want to go
over here with the task now it doesn't
return anything so we can just call here
void and as far as the functionality
inside of the function body we just want
to go with set tasks we want to spread
out all the existing tasks and then we
want to add the new one so we'll go over
here with tasks comma and then we will
add the task which was Prov divided to
add task we do want to pass this down so
add task is equal to add task and if
everything is correct we should get
bunch of red squiggly lines somewhere in
this case it's in the index DSX simply
because we haven't set up form to accept
any props so let's work on that we
already have D type task so now let's
set up our type here for the props I'm
going to call this for props and in here
I'm looking for add task function same
deal it's looking for this argument the
task one and it's actually type task and
then when it comes to the return we're
just going to go with void and then
right after our condition I think I can
remove that console log I don't think
there's a point anymore we can just go
with add task and essentially one by one
let's provide those properties we have
over here remember it has to be a string
so I'm just going to go with date then
I'm going to invoke get time method
and eventually I'm just going to turn
this into a string then I still have red
squiggly line
because I mean I actually haven't set up
the props properly my bad what am I
doing let me go here with add task and
this is actually going to be equal to a
form props
and now we get the correct red squiggly
lines where essentially we can see that
few properties are missing so let's
provide them we're going to go with
description so this one will be equal to
a text and also let's go with is
completed which we will hardcode and set
it equal to false now I don't have any
red squiggly lines and once we navigate
to the browser I'm actually going to
open up the components just so I can
see what we have as far as the state and
now let me go with first task me invoke
this and yep notice over here we are
successfully adding this task to our
list all right so we're pretty much done
with the form I don't think we're going
to work in that component anymore now we
just want to render the list and also
toggle the task remember it has that is
completed property which is Boolean um
and just like in the fundamentals
project we just want to display some
checkbox and then every time we will
click on that checkbox then we'll toggle
that value and actually before we
render the list I do want to right away
set up this function since we'll pass it
down to a list
component the functionality is super
straightforward where we want to go
toggle task now this function is looking
for the ID so so therefore let's right
away set up the inline type annotation
and let's say that ID is actually going
to be type string now as far as the
actual functionality we want to go with
set tasks and then remember when we
invoke map we get back a new array so
now I just want to iterate over the
array and if the ID matches the task ID
I want to set the task is completed to
the opposite value now if it's not the
case if they don't match then we just
return task as it is so let's go with
tasks map and yes as a sign not there
are Million Ways How we can write this
functionality I just went with this
approach so we're going to go here with
task then we'll check if task ID is
equal to ID we're passing in then we
want to
return this task with a new is completed
value so we want to spread out the
existing task and we want to go is
completed and set it equal to the
opposite so we're going to look for task
and then is completed now if it's not
the case then we'll simply return the
task and with this in place now we can
pass this toggle task down as well as
our entire tasks list so first prop will
be tasks and the second one actually is
going to be toggle task now we haven't
set up of course anything in the list so
all of that is coming up let me just
pass this down we're looking for toggle
task then let's navigate to our list and
first let's grab our task we will need
our type so import type task and that is
coming from my types yep that's the one
and let's set up right away the list
props so type list props and in here we
have tasks which is actually an array of
tasks and also we want to set up that
toggle task so toggle task same
deal it's going to have the ID and
actually that ID will be a string but
notice how essentially we're providing
an object correct so make sure you have
the same syntax okay good and in here we
want to the structure both of them so
tasks and toggle task and we'll set it
equal to list props beautiful and now we
want to iterate over the list display
all the items and also let's right away
set up the toggle task functionality so
we're going to go over here with Anor
list let's add a class name of list then
inside of the unor list let's go with
tasks. map let's invoke this and over
here we're going to have a task and then
for every task we want to set up the
return it's going to be a list item and
also we'll provide a key that's a must
so we're going to go here with task
ID Also let's set up the paragraph This
is where we'll display the task
description as far as the classes we're
looking for task and text and over here
let's set up task and description so we
have access to that and now let's set up
our input so at the very end over here
we're going to go with input now it's
not going to be a text actually we'll go
with checkbox we're going to go with
checked so it has this prop and we're
going to set it equal to task and then
dot is completed so if it's true then
the checkbox is going to be checked if
not then it's not going to be the case
and we'll right away add this onchange I
will pass over here the inline function
we don't need actually the event I
simply want to go with title task and
then I want to provide the object with
the ID property where I'm looking for
TAS ID now before you ask can you
essentially set up this
ID as a straight up argument so
essentially without that object yes
absolutely it's just my preference to
set it up as an object in this case and
with this in place we're done with the
list as well as toggle task
functionality so if I add a second one I
can nicely toggle over here this value
as well now if I'm going to refresh the
page of course I'm going to lose all of
the values since we haven't set up the
local storage yet and in fact this is
something we're going to do in the
following video okay so now let's just
add local storage to our application and
I want to start by navigating to the
browser to the application and I want to
remove the previous ones I believe I
still have values from the fundamental
section then we want to create two
functions one is going to be load tasks
so we want to load the tasks when the
application starts up and we'll also
have one to update the storage and since
it's a react project we can use use
effect and then pretty much every time
there's going to be some change in a
tasks list we will invoke the update
storage let's start with the
load tasks function so this function is
going to return an array of tasks as far
as the functionality we want to go with
stored tasks so that is equal to local
storage then we're looking for get item
that tasks something we don't have yet
and then we want to
return and then based on what we have in
the local storage either we're going to
return those tasks or we're going to
return an empty array so let's set up
turning operator we're going to go with
Json parse and we'll pass in stored
tasks that's not the case we'll return
empty array and then in here I'm just
going to provide a function and then I'm
going to invoke load tasks and then like
I said we also want to set up one to
update storage so every time we'll
change something about the list be it
add the task to the list or toggle D is
completed we'll update the storage so
update storage now this one is looking
for the tasks and actually it's going to
be an array of task now it's not going
to return anything so we're just going
to go with void and then we want to go
with local
storage then dot we're looking for set
item the name is going to be tasks and
we're going to go Json stringify since
we can only store strings over there and
we'll provide the tasks so this is how
we're going to create those items and
then when the project
loads this is how we're going to access
them like I mentioned since this is a
react project
we can go with use effect and then
pretty much every time there's going to
be some change in our dependency array
which contains the tasks we will also
invoke the update storage and we'll grab
the tasks value so now let me navigate
back to the browser or it's over here
everything is empty I have no tasks but
I can go with first task okay good
second task task notice how they are
actually saved in local storage I can
also toggle the is completed and then
once I refresh I still preserve the
values that should do it for typescript
with react section hopefully everyone
enjoyed it and up next we're going to
start working on a big typescript
project where we're going to implement
most of the things that we have learned
in fundamentals and react with
typescript sections
Can't find what you're looking for?
Get subtitles in any language from opensubtitles.com, and translate them here.