Week 2 Typescript
Summary
TLDRThis video script introduces TypeScript as a superset of JavaScript with added strict rules for better code behavior. It guides viewers on installing TypeScript and Visual Studio Code, along with essential extensions. The tutorial covers creating a TypeScript file, initializing TypeScript with a config file, defining variables and arrays with specific types, and using interfaces to define object structures. It also explains functions, handling optional properties, and creating custom types. The script concludes with compiling TypeScript to JavaScript.
Takeaways
- 🌐 **TypeScript Introduction**: TypeScript is described as JavaScript with superpowers, a superset that adds restrictions and strict rules for better code behavior.
- 🛠️ **Tool Requirements**: To work with TypeScript, the presenter suggests having Visual Studio Code and Node.js installed.
- 📂 **Project Setup**: The process of setting up a TypeScript project on a desktop involves creating a folder, navigating into it, and opening it in Visual Studio Code.
- 🔌 **Extensions Recommendation**: For enhanced TypeScript development, extensions like Auto Rename Tag, ES7+, and Prettier are recommended.
- 📝 **File Creation**: A `.ts` file is created for writing TypeScript code, with `TS` standing for TypeScript.
- 📥 **TypeScript Installation**: The script explains how to install TypeScript globally using npm on Windows or with `sudo` on a Mac.
- 🔄 **Initialization**: After installation, TypeScript is initialized to create a `tsconfig.json` file, which manages TypeScript code settings.
- 🔍 **Type Annotations**: TypeScript allows for the specification of types for variables to ensure type safety and correctness.
- 📚 **Interfaces**: Interfaces in TypeScript are used to define the structure of objects with specific types for each property.
- 🔧 **Type Definitions**: Types can be defined for values that can be of multiple types, known as union types, and are used for more complex data structures.
- 🔄 **Transpilation**: The final TypeScript code is transpiled to JavaScript using the `tsc` command, making it executable in environments that only understand JavaScript.
Q & A
What is TypeScript and how does it relate to JavaScript?
-TypeScript is a superset of JavaScript that adds strict rules and restrictions to help developers write more reliable code. It aims to calm the chaos of unexpected bugs by enforcing type checking.
Why might TypeScript be considered as having 'superpowers' over JavaScript?
-TypeScript is considered to have 'superpowers' because it provides additional features such as static types, which help catch errors at compile time rather than runtime, thus improving code reliability and maintainability.
What are the two software requirements mentioned in the script for setting up TypeScript?
-The two software requirements mentioned are Visual Studio Code and Node.js. Visual Studio Code is the recommended code editor, and Node.js is needed for running JavaScript on the server-side.
How do you create a TypeScript file in Visual Studio Code?
-To create a TypeScript file in Visual Studio Code, open the terminal within the desired directory and type 'code .' to open the directory in Visual Studio Code, then create a new file with a '.ts' extension.
What are the three extensions recommended in the script for TypeScript development?
-The three extensions recommended for TypeScript development are 'Auto Rename Tag', 'ES7+ React/Redux/GraphQL/JS/TS', and 'Prettier - Code formatter'.
How do you install TypeScript globally on a Windows machine?
-On a Windows machine, you install TypeScript globally by running 'npm install -g typescript' in the command prompt.
What is a TSConfig file and why is it important?
-A TSConfig file is a JSON file that helps manage TypeScript code by providing various compiler options such as file inclusion/exclusion, target JavaScript version, and additional checks to enforce code accuracy and strictness.
How does TypeScript handle variable typing compared to JavaScript?
-TypeScript requires explicit typing of variables, which helps catch type-related errors at compile time. JavaScript, on the other hand, infers types dynamically at runtime, which can lead to unexpected bugs.
What is an interface in TypeScript and how is it used?
-An interface in TypeScript is a way to define the shape of an object, specifying the types of its properties. It is used to ensure that objects conform to a specific structure.
How can you make a property optional in an interface?
-You can make a property optional in an interface by adding a question mark (?) after the property name, indicating that the property is not required.
How do you compile TypeScript code into JavaScript?
-To compile TypeScript code into JavaScript, you use the TypeScript compiler by running 'tsc' in the terminal within the directory containing the TypeScript files.
Outlines
🔧 Introduction to TypeScript
The script begins by introducing TypeScript as a solution to JavaScript's unpredictable bugs. It's described as a superset of JavaScript that adds strict rules to ensure more reliable code behavior. An analogy is used to explain TypeScript's role in maintaining order, similar to not allowing dessert before dinner. The presenter suggests installing Visual Studio Code and Node.js as prerequisites. They demonstrate how to create a TypeScript file and emphasize the importance of certain extensions for a better coding experience.
🛠️ Installing and Configuring TypeScript
The second paragraph explains the process of installing TypeScript on both Windows and Mac systems. It details the steps to initialize TypeScript, which includes creating a TS config file—a JSON file that manages TypeScript code with various compiler options. The presenter discusses the purpose of this configuration file, which acts as a roadmap for the compiler, setting rules for code compilation.
📚 Understanding TypeScript Variables and Types
Here, the focus is on creating variables in TypeScript and how it differs from JavaScript. TypeScript is praised for its ability to accurately infer types. Examples are given to show how TypeScript can define variables as specific types, such as numbers, strings, or booleans. The concept of 'any' is introduced as a type that can hold any value, but its use is discouraged for maintaining type safety.
🎯 Functions and Defining Types with Interfaces
The script moves on to discuss functions in TypeScript. An example function 'addValues' is created, which adds two values. The presenter then shows how to run TypeScript files using 'ts-node'. The concept of defining object structures using interfaces is introduced, emphasizing the importance of explicitly defining types to ensure type safety and avoid runtime errors.
🔄 Advanced TypeScript Features: Union Types and Type Conversion
The final paragraph covers advanced TypeScript features like union types, which allow a variable to be one of several types. The presenter demonstrates how to define a password field that can be either a number or a string. They also explain how to convert types and the process of compiling TypeScript back into JavaScript, which is the final output for execution.
Mindmap
Keywords
💡TypeScript
💡JavaScript
💡Visual Studio Code
💡Node.js
💡Extensions
💡TSConfig
💡Type Annotations
💡Interfaces
💡Type Definitions
💡Union Types
💡Transpilation
Highlights
JavaScript bugs can cause unexpected issues, and TypeScript helps mitigate these by adding stricter rules to JavaScript.
TypeScript is a superset of JavaScript that introduces restrictions to ensure better code behavior and predictability.
TypeScript enforces rules, such as ensuring that you 'eat your vegetables' (follow proper code structure) before 'dessert' (the final output).
To get started with TypeScript, you need to install Visual Studio Code and Node.js, and ensure you have essential extensions like Auto Rename Tag, ES7+ Snippets, and Prettier for cleaner code.
TypeScript requires installing and initializing it via the terminal using npm install commands, especially different for Mac vs Windows environments.
TypeScript's `tsconfig.json` helps manage configuration settings for compiling TypeScript code, setting parameters like the target JavaScript version and compiler checks.
TypeScript enhances variable declarations by allowing you to specify types explicitly, such as number, string, and boolean, for more predictable code.
You can declare arrays with specific types in TypeScript, ensuring the array only contains elements of a given type, avoiding type mismatches.
Functions in TypeScript can have specific types for their parameters and return values, ensuring they always behave as expected.
TypeScript allows the creation of interfaces that define the structure of objects, including data types for properties and optional fields.
Interfaces in TypeScript can include methods, and those methods must adhere to the defined function signatures and return types, like void for non-returning functions.
TypeScript supports unions, where variables can be multiple types (e.g., a password can be either a number or a string), increasing flexibility in code.
The difference between interfaces and types is clarified: interfaces are primarily used for objects, while types are used for union types and other constructs.
TypeScript code can be compiled into JavaScript using the `TSC` command, converting strongly typed code into plain JavaScript.
Using TypeScript ensures code is more maintainable, predictable, and less prone to runtime errors due to its strong typing system and compilation checks.
Transcripts
hi there you recognize those moments
when JavaScript is just throwing a
tantrum those unexpected bugs that pop
up when you think everything should be
working what if I told you there's a way
to calm that chaos introducing
typescripts so I hear you thinking well
what is typescript well think of
typescript as JavaScript with superpower
it's a super set of JavaScript which
basically means it adds some actually
restrictions some strict rules so your
code behaves
well let me give you an
example JavaScript might let you eat
your
dessert before your main
meal well typescript will not let you do
that it will check your plate have you
eaten your vegetables is your plate
empty yes well then you can have your
dessert
so basically typescript checks the rules
are you following the rules yet all
right so now that you um know that we're
going to use with typescript and that
typescript is just making JavaScript
better um make sure that you have
installed two things on your
computer Visual Studio
code and note
JS Visual Studio code you probably
already have nodejs just go to
nodejs.org and get it installed there
I'm on a Mech right now
and I'm going to show you how to get
started here so first of all on my
desktop I have um a folder called
typescript and I'm going
to let's
see I'm going to open up a terminal here
we go terminal I'm going to CD into this
folder
change directory I'm in the directory
now and I'll type code and then the dot
so it opens up inside this directory
inside Visual Studio
code by the way this does not work
automatically on the Mac um you would
have to go into Visual Studio code and
go to the command pellet uh so shift
command
p and you would have to install it like
this all right
okay anyways so let's go back to where I
was here I close this here um code and
it opens it up inside a visual studio
code all right great you can see it's
right here um also just so you know make
sure that you have these inst extensions
installed for me uh Auto rename tag I
mean you don't have to install them I
just think they're very good to use um
that is is if you have a beginning tag
and a closing tag and you change the
beginning tag it automatically changes
the closing tag then es7 plus and
prettier okay so install those two if
you want to read more about them you
click on one here and you can see you
can read all it does okay um same for
pretty here make sure code is
pretty yeah easier to read make sure you
install at least these three probably
you have your own preferences all
perfectly
fine okay good um so let's go back here
and just so you know um for
typescripts uh and javascripts
JavaScript you can run either in the
browser using an HTML uh file uh or just
like we're going to do now we're going
to run it in a note okay
all right to get started uh we first
going to create a file uh here we go and
I'm going to say type no I'm going to
call it
tutorial. TS Ts for typescripts you can
see if I type in jss it's a j script
file and TS is for a typescript file
there we go um we're going to write all
our code in here but to be able to do so
we need to install
typescripts all right so to install
typescript on a Windows uh machine you
do npm
install globally type
script you will see it doesn't work on
the Mac clear
instead I would have to do pseudo npm
install globally type
script there with the password for the
mac and it would install it that way
okay now that we have typescript
installed we should also initialize it
we did it as follows follows uh on a
Windows machine you do TS see typescript
in it or as I am on a Mac I have
to add Pudo in front of
it
enter and here we go we have our TS
config file which is a Json
file this file will help us to manage
our typescript code it has a bunch of
config configuration settings inside of
it the file includes settings for
various compiler options such as which
files to include or exclude the target
JavaScript version you want your
typescript to run with and additional
checks to tell your file how
um accurate you want to be how strict
you want it to be so basically it's a
road map telling your compiler which
settings to follow for now we're going
to leave all the settings the way they
are all right so now we're in the file
and we all know how to create a variable
for example let H equals
45 now typescript is already doing quite
a good job guessing what H is it is a
number that is right but we actually
want to tell we want to be accurate in
saying what it
returns so this will return a number
then
let job
equals a
teacher again JavaScript will guess what
it is it's a string it is correct this
is a string
indeed let is
fanastic equals to true what is this a
bullion will touch guess it right yes
it's a bullion this will return a
Boolean okay so now I've added three
more lines uh here for example let ages
equals and it's an array of four numbers
so what will this return this will
return
an
array
of
numbers okay if I would say this is an
array of strings you say this is not
accepted the type number is not
assignable to a type string unless of
course I would turn these into
Strings it would
work in that case number would not work
let's change it back to
number in some cases you're a bit sloppy
and you would not know what to
return then you could always type in
any or here is an array with a string a
number in a
Boolean so you can say it's allowed to
return anything inside this
array generally try to avoid any okay
now let's move on and uh look let's look
at
functions so I'm going to create a
function called add
values and it's going to be an arrow
function
there and the arrow function accepts two
values A and B and it's
returning A and
B There we
go now what happens if I console log
this so I'm going to console log this
function here values
there and I'm going to because right now
A and B are um defined as any so I
should be able to just call my
name so a equals and b equals so
together it should
be now what I should also do is to
specify that a is a string and B is a
string yeah a is of type string BS of
type
string then I want to check this file to
see if the console log is showing me the
same the right value
say to do that I am just going to
install a package called TS node so I
can just run this F file in the
terminal and
clear so now when I say TS
node
tutorial. TS I should
get and there we go so a is of type
string and B is of type string and the
return is also a string
so when I now save it and I run it
again it's correct if I want this to be
numbers let's say
40
and five those are two numbers I have to
change this into a number that's of type
number B is of type number and our
return is also a number save this run it
again
and you see it's 45 which is
correct okay now let's move on on how we
Define objects and types
ourselves so look at this object it has
an ID a model and a year yeah the car
has an ID a model and the year
now um T is already doing a good job it
says ID is probably a number the model
is a string correct and here is also
number but we shouldn't do this we
shouldn't let him assume so we should
Define the object by using an
interface so the
interface sort of
defines the typ script for the object so
we're going to include these inside the
interface uh and let's call the
interface by the way
car
interace and we add this but instead of
the values we're going to call say the
type so this is of type number this is
of type
string and the last one is also of type
number so now we can use this
interface right here so we can say
car is of
type
car
interface this means if I change this to
for example a string or a
uh yeah just a string for example it's
giving me an error here because this
should be a
number now what happens if there's for
example no age then I am getting an
error here because it's missing the year
to make this optional because these are
not optional at the moment all I have to
do is add a question mark behind it
okay so now that became
optional what I can do is I can console
log for example car
dot
model and if I now check this
I get
Mercedes but if I get card of year which
I have not
defined I
get
undefined okay can you see that
undefined um
clear so I could
say
um
if car
dot if there is no car
doe
then I can console
log um
no year for this
car else
I can console look
this there we go let's see if it
works oh
card car
oh there we go
clear no year for this car okay but if I
addit
year
2008 I'm going do it again I do get the
year all right now let's add a function
to this um interface so we could say
it's a function where it has um uh color
and all we do is we're going to on
solo the um yeah what should we say uh
gradients I don't
know so we're going
to gradient just a word okay um now this
actually not
defined okay um it doesn't exist in the
car interface we should actually added
added here so we're going to add the
function
here
um and this is actually not going to
return anything it's just going to
console Lo so void means not returning
anything and here then we're going
to add the
um
gradient and the gradient is going to be
of a type
string like that now there's
actually you could add it add the same
thing here but you don't have to it's
already defined here
okay so let's see now let's check the
car car
dot color and the color is black
car. color and we're going to send
black okay that's the
parameter
save and check it out black all right
now let's move on to the next step let's
say I
want um to check
a password I don't
know
um where
the
code comes in as a
parameter and I'm going to
console log and then maybe it's the
um
password and let's the code for the
password
okay
um now of
course what is code
well let's say the
password would
be uh 1 two three four
five okay then in that case the code is
if type
number right
but a password is not always a
number sometimes it's a number
or let's see it could even
be a
string okay in that
case Hello would be
accepted this is called a
union and well with
um objects we've kind of used
interfaces but um when it's aligned like
this we will create types instead okay
so interface are use for objects uh and
here we will use a type instead so we
could for example set type here and we
can call it
password field
type and we could copy these
there and place them
there and then instead here we could
type in
password field type like so great okay
so we have looked at how to install
typescript uh we have looked at how to
make them type specific we have looked
at
interfaces um and we l have looked at
how to create specific types um
now if you want to turn this now into a
JavaScript code all you have top type is
TSC and you see that
the um code that we have just created
here is now a JavaScript
code
great thank you for listening listening
and see you in the next lesson
Ver Más Videos Relacionados
Learn TypeScript For React in 50 Minutes - React TypeScript Beginner Crash Course
#06 What is TypeScript | Getting Started with Angular | A Complete Angular Course
Setting Up Vite and React for Chrome Extension Development
No BS TS #1 - Typescript Setup & Everyday Types
The Right way to write Nest.js & Typescript clean-code - SOLID
How to Setup Visual Studio Code for Web Development | HTML, CSS, and JavaScript
5.0 / 5 (0 votes)