Learn TypeScript For React in 50 Minutes - React TypeScript Beginner Crash Course
Summary
TLDRThis video offers a comprehensive TypeScript in React crash course, building on a previous TypeScript introduction. The instructor addresses the importance of TypeScript for scaling React applications and reducing debugging time. The tutorial covers TypeScript basics, including variable typing, interfaces, and enums, before diving into advanced topics like TypeScript with React Hooks and the Context API. Practical examples, such as creating a user context provider and form event handling, are provided. The script concludes with a demonstration of converting a JavaScript component to TypeScript, highlighting the benefits of TypeScript in understanding and utilizing libraries.
Takeaways
- ๐ The video is a continuation of a TypeScript crash course, focusing on integrating TypeScript with React to enhance application development.
- ๐ TypeScript is highly recommended for those learning React, especially for industry job prospects, as it is widely used and can prevent scalability issues.
- ๐ ๏ธ The tutorial covers the basics of TypeScript types, such as strings, numbers, booleans, arrays, and the 'any' type, which should be used sparingly.
- ๐ก Interfaces in TypeScript allow for the creation of custom types, which are particularly useful for defining props in React components.
- ๐ The video demonstrates how to define and use props with types in functional components, improving code reliability and maintainability.
- ๐ง Practical examples are given on using TypeScript with React Hooks, such as useState, to ensure type safety and prevent bugs.
- ๐ The script explains the importance of handling potential null values when fetching data or using APIs, emphasizing TypeScript's role in error handling.
- ๐ The use of TypeScript with the Context API is explored, including creating context types and providers for more complex state management.
- ๐ Enums are introduced as a way to define fixed sets of values, like countries, providing a controlled way to assign specific values in props.
- ๐ The video concludes with a practical example of converting a JavaScript component to TypeScript, step by step, to illustrate the process of migration.
- ๐ฎ TypeScript's ability to provide insights into library implementations, such as React's useState, is highlighted as a benefit for deeper understanding of the frameworks used.
Q & A
What is the main focus of the video?
-The main focus of the video is to provide a comprehensive TypeScript in React crash course, building on a previous TypeScript crash course, and covering topics necessary for using TypeScript in a React application.
Why is learning TypeScript important for React developers?
-Learning TypeScript is important for React developers because it is widely used in the industry, helps in building scalable applications, and can save time in debugging. It is almost a requirement in many companies for React development.
What is the role of TypeScript in preventing bugs in React applications?
-TypeScript helps in preventing bugs by enforcing type checking, which ensures that variables and functions are used with the correct data types. This reduces runtime errors and improves code reliability.
How does the video introduce the concept of types in TypeScript?
-The video introduces the concept of types in TypeScript by explaining how to define types for variables, such as strings, numbers, booleans, and arrays, and how these types help in maintaining consistency and preventing type-related errors.
What is an 'interface' in TypeScript and how is it used in React components?
-An 'interface' in TypeScript is a way to define a blueprint for objects, specifying the structure and types of properties an object should have. In React, interfaces are used to define the shape of props for components, ensuring that components receive the expected data types.
How does the video demonstrate the use of TypeScript with React Hooks?
-The video demonstrates the use of TypeScript with React Hooks by showing how to define types for state variables and how to handle form events with proper typing. It also explains how to use TypeScript to ensure that the state and props are used correctly within the hooks.
What is the purpose of the 'enum' in TypeScript and how is it used in the video?
-The 'enum' in TypeScript is used to define a set of named constants, which can be used to restrict a variable to a set of predefined values. In the video, 'enum' is used to define a list of countries, ensuring that the country property in a user object can only be one of the specified country names.
How does the video explain the use of TypeScript in the context of the Context API?
-The video explains the use of TypeScript in the Context API by creating a 'UserContext' that includes typed states and functions for managing users. It demonstrates how to define the context type, create a context provider, and use the context in components with proper type checking.
What is the process of converting a JavaScript component to a TypeScript component as shown in the video?
-The process involves defining types for props, states, and functions within the component. This includes creating interfaces for props, specifying types for state variables, and ensuring that functions handle data types correctly. The video demonstrates this by converting a 'UserProfileEditor' component step by step.
Why is it beneficial to understand how libraries like React implement their hooks internally?
-Understanding how libraries implement their hooks internally helps developers gain a deeper insight into how the libraries work, which can aid in more effective and efficient use of the libraries. It also helps in debugging and optimizing code, as well as in learning best practices from the library's design.
Outlines
๐ Introduction to TypeScript in React
The video begins with an introduction to a comprehensive TypeScript in React crash course. The presenter acknowledges positive feedback from a previous TypeScript crash course and expresses the desire to continue the topic due to audience requests. The main focus of the video is to teach the necessary TypeScript concepts for using it in a React application. The presenter emphasizes that while TypeScript is not strictly required, it is highly beneficial for understanding and implementing in React, especially for those looking to work in the industry or build scalable applications. The video also mentions a sponsorship by Brilliant.org, a platform for learning STEM-related topics through interactive problem-solving.
๐ ๏ธ Setting Up a TypeScript React Application
The presenter demonstrates how to set up a React application using TypeScript. They use the `vit` command to create a new project, choosing React as the framework and TypeScript as the language. The video covers the basics of defining variables with types in TypeScript, explaining the importance of type definitions for preventing type-related errors. The presenter also introduces the concept of arrays, the `any` type, and the creation of interfaces for custom types, using a `person` component as an example to illustrate these concepts.
๐๏ธ Building Components with TypeScript in React
The video continues with a deeper dive into building components in React using TypeScript. The presenter explains how to define props using TypeScript, emphasizing the importance of type safety to prevent bugs and ensure correct data handling. They demonstrate how to create a `person` component, define props with specific types, and use interfaces to enforce type correctness. The presenter also shows how TypeScript can help in handling null values and how to use enums to restrict prop values to a specific set of options.
๐ Understanding TypeScript with React Hooks
The presenter introduces the use of TypeScript with React hooks, specifically focusing on the `useState` hook. They explain how to define the type of state and how TypeScript can infer types automatically. The video demonstrates creating a toggle function for a component's state and how to handle form events with TypeScript. The presenter also discusses the use of unions to allow multiple types for a state variable, providing an example of a state that can be either a boolean or null.
๐ Working with TypeScript and Context API
The video explores the use of TypeScript with the Context API in React. The presenter creates a `userContext` and explains how to define the context type, including a list of users and functions for adding, updating, and deleting users. They demonstrate how to create a context provider component and how to pass the context value with the correct types. The presenter also discusses the importance of defining types for props when accessing children in a React component.
๐ Enhancing Components with TypeScript
The presenter continues to enhance the `user` component by adding a biography feature that updates based on user input. They explain how to handle form events and define the types for event objects in TypeScript. The video also covers how to create a context provider for managing user data across the application, emphasizing the importance of type definitions for functions and states within the context.
๐ Converting JavaScript to TypeScript
The video concludes with a practical demonstration of converting a JavaScript component to TypeScript. The presenter identifies the need to define types for props, states, and functions within the component. They create interfaces for the user data and the update function, ensuring type safety throughout the component. The presenter also highlights the benefits of using TypeScript, such as understanding how libraries work internally and improving code maintainability.
Mindmap
Keywords
๐กTypeScript
๐กReact
๐กType Definitions
๐กInterfaces
๐กHooks
๐กContext API
๐กEnums
๐กPropTypes
๐กVite
๐กBrilliant.org
๐กType Inference
Highlights
Introduction to a comprehensive TypeScript in React crash course, building on a previous TypeScript basics video.
Explanation of why learning TypeScript is essential for scaling React applications and its industry demand.
Demonstration of creating a React application using Vite, a tool for generating React apps with TypeScript.
Importance of defining variable types in TypeScript to prevent type-related errors in React applications.
Overview of different TypeScript types such as strings, numbers, booleans, arrays, and the 'any' type with its drawbacks.
Introduction to interfaces in TypeScript for creating custom types for objects, enhancing code reusability.
Explanation of defining props types using interfaces to ensure type safety in React components.
Discussion on the benefits of using TypeScript for handling bugs and ensuring data integrity in applications.
Tutorial on using TypeScript with React Hooks, such as useState, and the importance of type definitions for state.
Illustration of handling form events with TypeScript in React, emphasizing the correct typing for event objects.
Guide on creating a context using TypeScript in React, including defining context types and provider components.
Explanation of using enums in TypeScript to restrict variable values to a specific set, ensuring data consistency.
Conversion of a JavaScript component to TypeScript, demonstrating the process of adding types for props and state.
Insight into how TypeScript can help understand and work with library internals, such as React's useState hook.
Encouragement for viewers to learn from various sources and the importance of combining video learning with interactive problem solving.
Sponsorship acknowledgment and recommendation for Brilliant.org, a platform for learning STEM topics through interactive problem solving.
Final thoughts and call to action for viewers to like, comment, and subscribe for more content on TypeScript and React.
Transcripts
hey guys how's it going I'm back here
with another video and in today's video
I'm bringing to you guys my full
comprehensive typescript in react crash
course so this is a continuation from my
last week's video which was my
typescript crash course and I got a lot
of positive feedback from you guys and I
really wanted to make a video like this
because it was requested now you
technically don't need to learn
typescript or watch the previous video
in order to understand this one however
it would definitely help you get the
topics uh faster however in this video
um what we're going to be learning is
basically all of the typescript
necessary to understand in order to use
typescript in a react application so if
youve already been used to working in
react using JavaScript this video is for
you because I'm going to be not only
going over stuff like how to build an
application in V using typescript um how
to work with the different typescript
types when dealing with your variables
but also how to implement typescript in
Your Hooks
contexts and much more so in the end
we're going to be building a full
component that is going to be fully
written in typescript before we get into
the video if you could leave a like And
subscribe I would massively appreciate
it it is a thing that is really quick
for you guys to do and it will actually
help push my videos to more people so I
would be eternally grateful if you guys
could do that so um with that in mind
let's get into the video
this portion of the video is sponsored
by today's sponsor brilliant.org for
those who don't know brilliant is a
platform where you're able to learn a
variety of STEM related topics through
interactive problem solving like courses
they have courses related to literally
everything you might want to know
ranging from uh mathematics to different
sciences and even computer science I've
personally talked about brilliant in the
past to you guys and I've recommended
some of their courses like their llm
course and more specifically their
algorithms and data structures course
which can help you if you're actually
going to study for an interview but more
specifically I enjoy brilliant because I
believe that we have very similar styles
of teaching all of brilliant's courses
are designed in a way in which they
bring on real life examples to
facilitate your understanding of the
topic so if you kind of like my style of
teaching I definitely think brilliant
will be a good platform for you like
I've mentioned I've personally done some
of the brilliant courses in the past but
I wanted to actually give a shout out in
this video for all of their courses in
mathematics if you go to brilliant.org
and go to their advanced mathematics
course category you'll see that they
have courses ranging from uh stuff
related to pre-calculus to uh linear
algebra and Vector calculus and anything
that you would learn in a normal
mathematics degree and speaking as
someone who actually graduated with a
math degree um I can tell you that math
helps a lot with programming it's not a
necessary skill but it definitely levels
you up so I wanted to shout that course
out because I think you guys would
benefit a lot from it plus their handson
approach means that you're not just
passively watching their videos you're
actually actively solving problems that
you would in a normal day-to-day
scenario if you're interested in
checking them out I'll put a link for
brilliant.org padot Tech in the
description just for my viewers you guys
will get a 20% discount when you sign up
for their annual premium subscription
again it's uh brilliant.org / pedot Tech
and now let's get into the tutorial okay
everyone so right off the bat you see I
have here a small um vs code window
popped up and I'm inside a folder called
typescript react so I'm going to show
you guys how to install a react
typescript application but before we do
that I just want to give you guys a
brief explanation of why you definitely
need to learn typescript in order to
build react apps so if you're learning
react I assume is because you either
want to uh get a job in the industry or
you want to build an application and in
both scenarios I would 100% say that
it's necessary to get to understand
typescript because if you're learning
react or using react in order to get a
job in the industry I doubt that you're
going to be hired if you don't know
typescript because typescript is used in
almost every single company and if there
is a company that is still building
react applications using pure JavaScript
I would gladly say that I don't think
it's a good company to work on because
um the application will probably not
scale well and it will actually cause a
lot of problems that will end up in the
hands of you the developer so I think in
that scenario for sure you need to learn
this but also if you're building an
application on your own then you can
make this decision to learn typescript
as a technology as a language and spend
I don't know one or two days actually
just learning it and that will save you
months of debugging trust me in the long
run this will save you so much time of
debugging and it will actually make your
application scale way more than it would
if you were using just normal JavaScript
so now that I explained why you
definitely want to learn this
let's get to actually building the
application so uh like I said I'm going
to be using uh vit to build this so if
you've never used V in the past it's
basically this it's just a way for you
to generate your react apps just like
nextjs just like uh create react tap
however vit is a very handy way for you
to do it so in order to create an app
with vit I'm going to run npm create
v um and then I'll say at latest just so
we get the latest vers version and then
I'm going to put a dot over here so I'm
going to press enter and uh it's going
to ask us what kind of uh framework we
want to create a vit app with so you can
actually use it for a lot of different
options I'm going to create it with
react and then you can see V actually
allows you to just choose the language
straight up in the terminal so I'm going
to choose typescript and as you can see
it will have generated the app but to
actually run it I have to run the
command npm install to install all the
packages in the package. J B on and uh
when that's done and we want to run the
app I can run npm runev but for now
we'll actually not run it I just want to
open up one of the components over here
um and start explaining to you guys
using this as a template to explain to
you guys how type script will actually
work so let's keep this simple right uh
if you've never worked with uh with
typescript before it is important for
you to understand the different types
that exist inside of typescript and I
will just briefly mentioned them so you
can create variables right so for
example you can create the variable name
and set it equal to a string called
Pedro but in typescript you have to
define the type that this variable will
have so since this is a string I have to
come over here and say that it will have
a value of string because if you don't
do that then um typescript won't
actually allow you to create this
variable if you are in what is known as
strict mode which by the way I
definitely recommend watching my
previous video to understand this is
just a way for you to um that is
determined for you to actually keep
checking to see if you're using
typescript correctly but defining types
like this prevent you from later on
coming over here and saying name is
equal to 45 because then it will give
you an error saying that you can assign
a a number to a string so this is basic
the basic concept of what typescript
does right and in react this is great
because any variable you want to create
right name age you can Define over here
the actual value or the type and set
something I can create like a is married
bullion and just say that this is a
bullan and set it equal to true or false
so you kind of get the idea now I'll
just uh list three more types that I
think are important for you to
understand uh before we get into
actually doing what is mostly uh just
pure react typescript stuff this is more
General typescript but this is just what
I think is important for you to get
first so to make a list for example a
list of uh I don't know numbers like a
list of Ages uh uh you actually just set
the type like this you say it's a number
array just like this and then you set it
equal to uh a list of numbers right so
if we ever work with lists which you
probably will a lot um you have to
Define it like this uh what else so
there's the any type so if you have a a
thing that you actually don't know what
the type is you can use any and then you
can see that I can set this equal to
anything like I can say person is equal
to a string and it won't won't actually
give us an error but the thing is I
don't recommend using any because then
it def defies the whole purpose of using
typescript right and the last thing that
I want to show to you guys is is the
idea of creating um interfaces so
creating your own type if I were to
create a component over here now we're
mostly going into to what uh typescript
you actually use in react so if I were
to create a component over here for
example I create a component called
person right first of all uh the
extension is not going to be JS and it's
not going to be jsx it's going to be TS
or TSX now if you're going to be
creating a component inside of this file
you definitely have to make this into a
TSX or else it won't work if you make it
like this uh it usually used for files
like creating your types creating
functions and stuff like that but if
you're going to create a component
definitely make it
TSX then over here let's create a
component right I'm going to export
const
person and let's make it a simple
component uh I'll just return the text
person now over here in the app. CSX
let's import this
component so I'll say
slashers and let's import person over
here
now what I want to introduce to you guys
is the idea of how do we Define props
using typescript because if you don't
recall when if I wanted to for example
take in some props for an individual
person over here right if I wanted to
say that the props in this is uh and
I'll say props over here and I'll say
that it will take in the following
things a person can take in a name right
let's say Pedro it can take in an age
let's say 22 and uh it can take in is
married right which I'm not married so
I'll say false right so it takes in this
props and we have here props at the top
and actually I just want to display that
information so I'll create here A P tag
and I'll say um first descrip the name
so name and then say props
name and then I'll do the same for
age um age and then I'll say props that
Ag and then over here I'll just
say this
person um and then I'll just change this
depending on the Boolean so I'll say
props do is married and I'll say if it
is married then this person is married
if the person is not married then I'll
say is single right so what if I want to
create a component like this and reuse
it how many ever times I want to I'll
even create another one just as an
example
um let's say I don't know
Colin
24 and also not married or actually
let's make him married so true if I
wanted to create this you can see
there's a red line over here because it
says that parameter props implicitly has
an any type so this is actually one of
the best use cases for typescript in
react because the following reason when
you create a component if I were to come
over here and I were to actually pass in
a string for age instead of a number it
would actually work the same so let's
test this out let's run this thing I'll
say npm run dep and let's grab this and
then just paste it over here okay so
this is the app right now right it shows
the two people but if I were to change
this to a string you see that it still
show shows the same thing it shows ages
22 right which means it must be working
right if I Chang this to uh I don't know
a list of strings then it will probably
give us an error visually speaking but
it doesn't even give us an error
visually speaking which is crazy right
it's just showing what what's there so
that's the thing uh with uh typescript
um or with react in general props can
whenever they have an implicit it any
type which means that since we didn't
Define this type the type for props it's
assuming that the type is any right um
it can actually show us no visible sign
of of actual misconduct in our code like
this so it seems like everything is
working perfectly but in itself if we
ever use this variable for anything more
than just displaying this it can
actually cause some bugs because it's
not the type that we wanted it to be so
this is this is kind of why we
definitely want to Define the types now
you've seen this before if you've ever
worked with prop types which is
something that comes directly with react
however uh typescript makes it also very
easy to do the exact same thing which is
Define exactly the type of props you
want and the way we do that is by using
what is known as an interface so like I
said uh there are some primitive types
in typescript like string number and
Boolean but you can actually create um
custom types that define object object s
they are known as interfaces so I'll
create a interface called props and I'll
just assign the props of this component
to be equal to that so we want this
props object over here to have three
Fields name age and is mered so we'll
come over here and we'll Define the
three Fields like this so I'll say that
this has a name which is a string it has
an age which is a number and it has has
an is married which is AUM so now
typescript doesn't give us a red
squiggly line anymore because it knows
that um we have defined the correct type
and more importantly you see this is a
Boolean right so if we were to use this
bul and wrong over here we're definitely
using it right we're asking okay if the
person is married if true then do this
if false do this right but if we try to
for some reason display the Boolean as a
as a string right right so I said props
isar we'll see that nothing really
happens but it also doesn't show it in
our screen but if we were to compare
this to something like uh I don't know a
name like Pedro you'll see that
immediately it gives us an error because
the comparison seems to uh try to
compare to things that are not of the
same type which means that typescript is
definitely checking almost all
interactions that you have with your app
um and by Def your prop like this it
makes it easier for you to not cause
stuff like what I did before because now
if I were to change this to a string it
immediately notifies us and I think it
also um might show over here um it
actually depends a lot on how you define
your TS config apparently doesn't seem
to be doing that um but if we were using
uh some sort of uh linking Library like
is lint um it could actually manually
trigger a break in our app so we can
actually have a more clear visible error
um if there's a typescript error now in
this case we just get the red squea line
which let us know that this isn't the
correct type but as you might have
noticed this is really useful because
also you can just make multiple types in
your app you can actually uh if if this
should define a person right we we
called it person over here so instead of
putting props we could actually just
call this person and then use this in
many different places in our app maybe
when we're trying to deal with data
Maybe when we're making a query that
grabs back per people right so we could
do something like that also if we wanted
to make this into a list right uh the
props is actually a list of people I
could actually just put the array over
here and um Loop through this props uh
that is now is an array it's not an
object and display the information just
like I said it would so um you can see
how useful defining props in your types
actually is now one reason why this
might also be very useful is um dealing
with bugs with bugs where you're you're
actually rendering a component based on
some sort of I don't know function right
that makes a request let me create an
example here like fetch
user and as a an example over here I'm
not actually going to be fetching
anything imagine that this returns back
uh an object for a user right it returns
back uh name is equal to
Pedro um
age is equal
to um 22 but then is
married is equal to null right so
imagine that this is what it's returning
and then over here I grab back the user
user fetched equals to fetch user let's
pretend we call this function and I pass
uh the information User fetched name
user fetch. Ag and and then user fetched
dot is married this will give us an
error because it is saying that it can
be null so this kind of forces you to
even when you're fetching data um from
an API or something to actually make
sure that you're handling cases in which
the data is null so that um inside of
this function I would probably make a
call like oh if any of the fields are
null then display an error so it will
force you to actually error handle
everything which is great for preventing
bugs okay let me just contrl Z all of
this um and let's move on from the
interface part of this tutorial now the
next thing I think is important for you
guys to understand is using uh
typescript when you're working with
certain hooks so let's as an example
over here inside of the person's uh uh
component create a hook right let's
create a a state um called um use State
and this state will be a button which um
will toggle some sort of uh will toggle
if it shows the information or not right
so I'll say show info or
is show info and the other one is set
show
info so I'm going to wrap all of this
around with the is show info and we only
want to display this information if that
Boolean is
true and um I do have to put this to
wrap all of this around and I probably
need to put a small bracket over
here just like this not bracket uh a
small fragment and then this how we
normally would do with JavaScript is we
would actually put the initial value of
the State uh to actually infert the type
so if this is a Boolean we would first
put false and then basically react would
know that this is is AIA right um but
the problem is that um things can happen
right I could come over here and say set
show info is equal to Pedro now because
typescript already is inferring that
this is a Boolean it actually will
already in enforce this um for us so we
actually don't have to Define any Types
on the use State however it's still
highly recommended that you put the
actual type um inside of the state so
that you actually are sure that you're
using it correctly so the way you set
the type for this or determine the type
for this is by adding uh a little thing
over here and writing the type so I'll
say B just like this and the great thing
about this is sometimes uh the type of a
state can be something like a Boolean or
a string or something but it could also
be F null right it can also be empty
data so when you're working with a
situation like that imagine that I want
to accept it to be false or true but I
also want to accept it to be no um you
can actually use what is known as a
union so a union allows you to um say
that this type over here will allow
either one thing or another so by doing
by by adding the union like this you can
say that this accepts both Boolean or
null so you can see null doesn't have a
right Squig line anymore but also true
will not have it false will not have it
but Pedro will because it's not part of
the type unless I say that a string is
also allowed over here so we'll keep it
actually just as a bon that was just a
tangent that I wanted to show to you
guys and let's create a function called
toggle uh
info um and this function is pretty
simple whenever we click on it we just
set the show info to be equal to the
previous value and the opposite of what
it was before so uh if it was true it
would become false if it was false it
will become true and then I'll put a
button over here that will say
toggle info and we'll set the onclick to
that now this should work as you can see
over here uh if I click on toggle info
it should show that if I click on this
one it should show the other one if I
click again it should hide and it works
perfectly right but the important thing
is that we are sure that our state has
the correct type now what if we have a
state that is a little bit more
complicated instead of just a a button
imagine we have an input right we have
an input over here which will be a will
accept a text and I actually want to
have a state that allows me to type
something in my screen like a mini
description of this person right so what
if that's a situation I want to have so
the way I'm going to do it is I'm going
to have a little uh P tag over here
which is going to say something like uh
let me grab the name so Props do
name uh bio something like that and then
over here I want to display some sort of
biography of this person but this
biography will only be determined as I
type on this input how would I do that
well first of all let's delete this and
let's create a state that is going to
keep track of what I'm typing on the
input so I'm going to say const is equal
to use State again this will be a string
so I have to Define thep over here and
initially it will be an empty string so
actually in this situation it's a great
moment for us to maybe say that this
could also be null instead of empty
string because that's just an easier
identifier right over here we can say if
uh let's actually create the name of
this state let's say per bio bio yeah
I'll say person bio and then set person
bio something like this so we can say if
person bio is equal to
null then we just want to say something
like uh no
bioavailable but if it is not null then
I want to set it equal to person bio uh
if you're checking for uh something to
be null you can actually not even do
this you can just say okay if not person
bio then uh show this because this is
the same thing as asking if person bu is
equal to no so now let's implement the
functionality oh and also let me delete
this because we're not doing that
anymore uh let me write the
functionality for typing on this input
and being able to store that value
inside of this because this is what
where I'm want to get I want to show you
guys how to deal with typescript in
situations where you're working with
form events because that's a little bit
weird when you're starting out so inside
of this input we're going to have an on
change right and it's going to call a
function called handle change and let's
create that function const handle change
is equal
to uh a normal function that just sets
the person bio equal to whatever the
value of this input is so in this
function we're going to have an event
right but the problem is I can't just
say event. Target
value because this has no value you see
it hasn't any type now what is the type
that we put for this event well this is
a predetermined type that already comes
with react if we if we want to so um the
specific type for when you want to grab
a change event from an input is defined
like this it is called react do change
event so whenever you have an input um
that you're you're using the unchange
and you want to grab the type from that
it is the change event from that input
and then you specify inide of this thing
which specific type of input or form
element um you are describing in this
case it is an HTML input element now
this seems weird but this is exactly the
type specific for the event inside of
the unchange function um and if you ever
forget this don't worry if you do a
small Google search you'll find the
answer for this because I remember when
I was learning this I was like I'm never
going to memorize this um until I did
but after a while right because it took
me a while to memorize this but I could
just search on Google whenever I wanted
so you see in this case this would work
and we could see that this would
actually generate the app that we want
like it says right now no bio available
but I can say Pedro is a very nice
person and it works perfectly so this is
uh kind of the idea for this
specifically um there are other event
types for example if you I know this
isn't a form but if you had a form and
you had a handle submit function that I
mean it's not applicable to this example
specifically but um you guys definitely
ran into a situation where you had a a
function that submits a form um and you
wanted to grab the event uh inside of
this function the type for that would be
react do form event
because it's a form and then it would be
an HTML form element so just memorize
this if you're interested but if you
ever have an un unsubmit uh you can do
that and then you can use this event to
do something like prevent default or
whatever you would want to do in this
scenario but this is just some basic
form events uh that I think are
important for you to understand and
there are specific types okay everyone
so now that we dealt with some form
events um I think it's time for us to
get into a little a little bit more
complicated stuff so what I want to
teach you guys is how to correctly use
typescript when working with the context
API and this is a little bit big because
um it allows you to understand a lot of
type uh interface creation and defining
types with different um hooks in react
like the the use context hook right so
what I want to do is to continue this
example that we've been working on so
far I want to create a file called the
user context
so I'll create a file called the user
context do um TSX so let's create a file
over here called the user context
provider and this will actually be a TSX
file because we're going to return back
a custom uh provider component for this
uh context that we're going to create so
first things first um I know this is
called person but let's change the name
of this to user because I feel like it's
more uh it's an easier thing to
understand uh when we're working with uh
websites instead of person and I'll
change all of this and I'll keep the
name of the file as person whatever but
one thing I want to do is you see that
this user type over here was created
inside of this
component if we're using the context
API uh and and we want to work with it
we probably want to keep them separate
we want to create actually a type for
the props over here not call the user
because not
necessarily they will be the same thing
in this case they kind of will but um in
many other scenarios they might not be
and inside of the user context provider
we'll create the user type or just user
right and we'll export it for here from
here so that it can be used anywhere
else in our app it's better keeping it
here than keeping it inside of
uh an individual component and then we
have to create what is known as the
context type because uh we're going to
create a context that is going to
include not only um a list of users but
also a function that is going to um be
able to add a user to a list of users um
also a function that is going to be able
to delete uh user from the list want to
update and one to just see the list of
uh users so it's a very simple crud um
app inside of this context so let's do
that let's create the interface that is
going to actually represent what the
context will return so we'll call it
user
context type and inside of here what do
we want we want to have a list of users
so I'm going to say users and it's going
to be uh user list but it can also be
null because imagine in a normal app we
would probably be fun fetching this from
an API and the list can obviously be
null so we have to account for that then
um we want to create a list uh or
actually have here a function for adding
user which will probably include um a
user inside of here so uh we can Define
the actual type of user like this by
seeing that the function will have an
argument called user and its type will
be user and we need to actually add a
return type I haven't explained this yet
but when you define functions instead of
interfaces you have to Define it like
this um the add user function will take
in a user and it will return void so we
can just do it like this then we want to
have the same thing but for uh updating
deleting and reading so uh reading
actually is okay we can just use the
list of users over here to read so for
updating um we could for example take in
over here uh ID of the user which would
be a string obviously this is all
examples but would be a string and then
we can also take in um I don't know
the the is
married for the user this is the thing
that we're trying to update and we can
take in the new value for it and um
actually we don't even need to take that
in because uh we can just change it to
whatever it is like the opposite of what
it is right now and then for delete
user we can just take in the ID of the
user and delete it from the list now
this is the actual what what we're going
to have inside of the context this is
what we can access if you here I'm
assuming you're used to the context API
so you kind of understand but the thing
is we're going to have a context that is
going to pass in all of those values so
in order to determine that that's
actually how the context is going to be
I'm going to come over here and create
the context I'm going to say use
user
context is equal to
create
context and then inside of this we can
actually put in uh the user context type
to tell react that this is has to be
what we pass in to this context we also
have to obviously import the create
context as you can see from react and uh
we have to P pass a type over here
so what I like to do is I like to put
pass in the initial like type for this
so I'll create a state called um context
initial values and it will just be an
object containing uh users and its
initial value will be uh just an empty
array then or null
actually then for add user we can just
say that the initial value is just a
function that returns null as well uh
update
user will be a function that returns
null delete
user is just a function that returns n
as well so this is just so we can have
an initial value for this context over
here and it stops giving us an error
right because remember this context
requires an object of this type so here
not necessarily this is how the data
that we're going to be returning uh
because in inside of this uh file we're
going to deal with fetching data
updating and doing all those stuff but
for now let's just pass in an initial
value like this then since we now have
this user context let's create the
provider so the way we do this is we
have to create a component called the
context user provider so I'm going to
say const user provider and this
function will take in some props
obviously and um the
prop that we actually really want is
just the children of whatever we wrap
this component around so down here we'll
just return back uh for now nothing but
then we'll return back the
props children just like this now you
might realize that it gives us an error
because it says that it has an any type
now if I were to click this it would
Define the type for props like this but
the thing is when you ever have to
access the children from a prop in react
and you're using typescript so the way I
would do this is I would actually create
over here the interface for props again
but just for this one and I would just
Define the children type as a
react. react node this is how I normally
do it uh for detering determining a
children when accessing it using
typescript you'll probably run into this
in the future so it's good to memorize
this specifically so we'll create this
user provider and the great thing about
this if you've never actually done this
kind of formatting for creating uh
providers and contexts is that inside of
here I can create the functions that are
going to be returned back inside of this
uh context and create actual States
because now it's all inside of this
component so we can actually create
States so I'll create a state called
users and set users now what type this
is is um a list of users so I'll say
user list and it can also be null for
recall this is specifically the way we
defined the users's type which means
that uh initially it will be null but
let's imagine that uh we'll have a user
fact over here and in this user fact in
this example I would
uh fetch some data over here uh and
return back and set the users to be a
list of the following
thing uh let's create a fake user over
here so we'll say name is equal to
Pedro age is equal to 22 and is married
is equal to false so obviously I'm just
doing this as an example but inside of
here you would fetch data and set the
users equal to that data but since I
don't have any API to fetch this I'm
just setting the users to the to this
fake data that I'm putting inside of
here here but at least we can now use
this users list right now what I want is
to wrap all of this around with the user
context provider so I'm going to say
user
context
um.
provider then over here I'll do the
exact same thing user context. provider
and I'll pass in the
value for this context as uh we only
have right now users so I'll say users
but right off the bat you can see that
there's an error because it is following
it's it's it's missing the following um
properties add user update user and
delete user so you might see already
that it is actually uh checking to see
if we're actually passing the correct
information and it I'm happy that we
were able to actually Define the types
for this context up here at the top so
it's telling us that we definitely need
these three functions so let's just
create them not going to actually
Implement them but let's just do it
const um add
user um and it requires uh
user and let's actually just return null
for this one and then pass in over
here uh then let's do the same for
update and delete both of them I think
they just require an ID which is a
string so let's just do that and they'll
both return n as
well and delete user and now let's pass
them and you see that as we pass them
they will uh the the right cular lines
will actually disappear the only one
here is uh this one because apparently
has no closing tag so let's check what
this is uh oh yeah we should have put
this over here and then close this and
you'll see that now our context provider
works perfectly which means that if I
wrap all of this around with the user
context or user provider actually and I
import that
component means that now inside of this
person component over here I could
technically uh access that by using the
uh use context hook if I pass in over
here the user context that I have to
export actually
user context right if I uh import that
user context
uh why is it not importing
it uh sorry about that let me just uh
try to import
this over
here uh import
from slash user context provider and let
me import the user context if I do that
and I put this oh actually I have to
pass this over here not there sorry
about that but if I do this um you'll
see that it autocompletes for us see it
says it knows exactly the types that
this context can return so it can return
a users it can return an update user it
can return a delete user and so on so I
hope you kind of got the idea I know it
it feels a little bit convoluted but
whenever you work with the context API
using typescript this is kind of how I
would go about it I would Define a type
for the data that you're going to be
manipulating or using in this context uh
a type for actual the return values of
this context then pass all of those
types to their individual respective
places and then actually make sure you
pass them as the value of that provider
so this is kind of how a context would
look like in typescript now moving on
from this uh I want to actually add a go
back to this thing that I was working on
right and show you guys a concept called
the enum which is actually a great way
for you to define a specific type of a
property inside of your application
especially for situations like this
imagine that we want to add something to
this props we want to add the country in
which the user was born in but the thing
is there's only so many countries
there's actually a specific list of
countries in the world and it's a
defined amount so you don't actually
want to leave this up like like up to
interpretation you don't want to make
country be a string because there's
actually a specific uh amount of options
that can go inside of this type so what
you can do is create an enum for this so
I can say enum
countries and then over here I can
actually Define a specific value for
each of the countries for example I can
make Brazil as one of the options and
set the value of it to
Brazil then I can make friends an option
set it equal to friends I can make India
an option and set it equal to India and
so on right I'll just put uh United
States as an option and set it equal to
United
States and then over here instead of
having uh country as a string let's keep
it as a as a country right and then down
here I'll just say uh p uh country of
origin is equal to props do
country uh oh I I have to wrap this
around
sorry props do country now you'll see
that first of all it's giving us some
red squiggler lines because we haven't
defined the country over here now what
do I put for this do I just put a string
do I just put Brazil well it will say
that we can't do that because Brazil is
not assignable to the type countries
actually with enums you can do a really
cool thing which is if I export this
enum
type right I could come over here and
import this like this uh
countries and then just choose what
country I
want like this because if you actually
uh had this as an open-ended option I'll
show you what could happen so let's do
country and let's do countries dot I
don't know
India and keep it like this right now it
allows us for to us to have actual
control over exactly what is displayed
over here because because you see all of
them are in capital letters right but if
this was a
string and uh I wanted to actually just
write Brazil over here you'll see that
it would allow me to whilst the one I
used the enum um is Captain in capital
letter so it allows you to keep some
standard and actually um keep users from
coming here and writing something like I
don't know wakanda right which is not a
country in the real world but it's clear
really allowed here makes us have some
control over that so using enums is
really cool and really important in my
opinion okay guys as uh final part of
this tutorial uh like I said I want to
show you guys how to convert a component
that was previously written in
JavaScript and make it into a typescript
component so as you can see I made this
component over here called user profile
editor it's a pretty intermediate
component with like a bunch of different
stuff and I definitely want to make some
changes that you've learned in this
video video that will allow you to uh
stop having some red squ lines because
uh no types were defined right so right
off the bat um I want to take a look at
the props right let's start with the
props um I see that there's two props
user and on update so let's create the
interface for
props and let's put those two types user
and I don't know the type for that yet
but then uh I'll put that on update um
now let's see what they what both of
these types look like so let's go to
user where is user used so I'm going to
contrl f and let's see where user is
used so it's we see already it's used
inside of the on update um but it
doesn't seem to be used Oh see it's used
over here it's used um to Define two
different states so it's used to define
the name and the email so those are two
different things that definitely need to
be in uh the user type now since there's
multiple things inside of a user a user
will be an interface of its own so let's
say
interface
user and let's grab the name the name
type which is probably a string right
I'm just assuming here and email will be
a string as
well now um is this correct is there
more that we can add here um let's take
a
look seems like no
not so I'll just actually set the user
equal to this
perfect now let's take a look at the on
update seems like on update is not
returning anything it's just making a
call which means that I know that it
will be a function that returns void but
it takes in a user and also uh it seems
like it Alters the value of user so
actually um it just actually takes the
user as an argument so we'll cre we'll
say that this function returns void but
it takes in an object like user of type
user perfect so now it seems like that's
working and how I def I say that this
props is equal to that interface well by
just doing it like this now let's take a
look at what else we have to do there's
more red squiggly lines well there's a
handle submit over here and we've
actually dealt with this in the past
right um we have to in order to grab
this event we have to Define its type
and if you remember I'll give you like
10 seconds to see if you actually
remembered uh the way you define this is
by saying react. form event HTML form
event or form element this is for the
handle submit not for the AR change and
it seems like actually now everything is
fine right so do you notice anything
else that we probably want to do even
though it doesn't actually show us an
error well if you didn't notice we
haven't defined the types for the states
now it's inferring the type because we
passed the prop which we Define the
their its types over here but we still
do need to set up the types for the
states so I'm going to come over here
and say that the type of this is
string and the type of this is also
string and now we officially converted
this whole component that used to be
JavaScript into a typescript component
so if you're migrating from a Javascript
app to a typescript one uh this is the
kind of work that you would probably be
dealing with uh maybe if it's a more
complicated one uh more complicated
component you will probably have to
spend more time but I think that you got
the idea from this now one cool thing
about using typescript is the fact that
it allows you to understand how
libraries work internally way easily for
example if I click on the US state we
can actually see how react defined the
use state right see it has some types
specific specifically um these are are
known as generics uh I didn't explain
this video but um you would understand
if you watched my other video but um you
can see that you can see all the types
and different typescript uh
functionality that is implemented with
react and their specific hooks now if
you were working with any other Library
you could see it as well on your own and
um it actually helps a lot understanding
how how how react works as a as a
general thing thing like you just um
take a look at how libraries Implement
their own things and how the things that
you're using were actually made so this
is basically it for the video If you
enjoyed it please leave a like down
below and comment what you want to see
next subscribe cuz I'm posting every
week and I would massively appreciate it
again thank you so much brilliant for
sponsoring this video I definitely think
you guys should check them out because
um just watching my videos it works but
the thing is always complimenting with
knowledge that you can gain elsewhere is
really important and you would
definitely help the channel if there's a
way for you to help the channel while
also learning a lot is by doing that by
checking them out and I'll massively
appreciate if you could do that so yeah
that's that's pretty much it really hope
you guys enjoyed it and I see you guys
next time
5.0 / 5 (0 votes)