Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

In order to build applications with angular you need to be comfortable with TypeScript so in this section

I’m going to introduce you to the fundamentals of TypeScript and object oriented programming
principles so by the end of this section you will have a good understanding of type annotations arrow
functions interfaces classes constructors access modifiers properties and modules if you’re familiar with
this concept and know how to implement them in TypeScript feel free to skip this section and move on
to angular otherwise you really need to watch every lecture in this section so now let’s get started So
what is TypeScript TypeScript is not an entirely new language it’s a superset of JavaScript so that means
any valid JavaScript code is also valid TypeScript code but TypeScript has additional features that do not
exist in the current version of JavaScript supported by most browsers out there for example in TypeScript
we have this concept of strong or static typing if you have worked with languages like C# and Java you
know that in these languages when we define a variable we need to specify the type of that variable in
TypeScript typing is optional so we don’t have to use this feature but using this feature makes our
applications more predictable and it also makes it easier to debug them when something goes wrong
TypeScript also brings quite a few object oriented features that we have missed in JavaScript for a long
time we have the concept of classes interfaces structures access modifiers like public and private fields
properties generics and so on you’re going to learn about this intersection another benefit of using
TypeScript is that with TypeScript we can catch errors at compile time instead of at runtime but of course
not all kinds of errors but a lot of errors so there is a compilation step involved and when we compile our
TypeScript code we can catch these errors and fix them before they’re playing our application and finally
another benefit of using TypeScript is that we get access to some great tools out there one thing that I
personally love about TypeScript is the intellisense that we get in our code editors again you’re going to
see that in this section the touch script is a beautiful language and it’s basically a super set of JavaScript
so any valid JavaScript code is also valid TypeScript code now the browsers out there they don’t
understand TypeScript and it’s very unlikely that they’re going to support it in the future so we need to
compile or more accurately transpile our TypeScript code into JavaScript so this is part of building our
application whenever we build our application TypeScript compiler kicks in and it transpiles our
TypeScript code into JavaScript code that browsers can understand now that’s enough introduction next
I’m going to show you how to install TypeScript and write your first TypeScript program in this lecture I’m
going to show you how to install TypeScript and write your first TypeScript program so here we’re in the
terminal we’re not going to work with angular in this section we’re going to purely focus on TypeScript so
first we need to install TypeScript globally on our machine so NPM install dash G which stands for global
TypeScript of course if you’re on Mac you need to put sudo at the front beautiful so I have installed the
latest version of TypeScript which is currently version 2.3 point 4 now we can type TSC which stands for
TypeScript compiler dash dash version again you can see that I’m running TypeScript 2.3 point 4 alright
now I’m going to create a new folder for this section so let’s call this TTS hello let’s go to this folder here
I'm going to create a new file and open it with VS code so code main dot TS so now I’m going to write
some plain JavaScript code and I want to show you that all this JavaScript code is also valid TypeScript
code so first I’m going to define a function let's call this log that takes a message and here we simply log
that message on the console like this then I’m going to declare global variable let's call this message and
set it to this string hello world finally call our log function message so this is just plain JavaScript code
right save I can the terminal we need to transpire this TypeScript file into JavaScript so TSC or top script
compiler main dot TS now if you look at the files in this folder look we have main dot JS and main dot TS
now this transpilation or compilation step when you are building an angular app happens under the
hood so you don’t have to manually call the TypeScript compiler in fact when you run your application
using Ng serve angular CLI falls TypeScript compiler under the hood to transpile all our TypeScript code
all right now let's open our main dot JS file so code main dot JS so it’s exactly the same code that we
wrote but now it’s in the JavaScript file so all JavaScript code is also valid TypeScript code I’m going to
terminal I can execute this code using node so node main dot JS and we got the hello word message on
the console so from the next lecture we’re going to look at specific features of TypeScript that we don’t
currently have in JavaScript alright let’s explore TypeScript by looking at variable declarations so in
TypeScript there are two ways to declare a variable you can use the bar keyword which we have seen in
JavaScript like bar number we set it to 1 or we can use the let keyword so let’s count with you now
before I explain the difference I need to clarify that the left keyword is also being added to the JavaScript
it’s a JavaScript has a few different versions we have ESP five or ecmascript 5 which is the version of
JavaScript supported by pretty much all browsers out there in around for a long time now we have Essex
which is a newer version and it was introduced in year 2015 and from that point the ecmascript team
which is the team extending JavaScript you set it to use year number instead of the version number so
we have like more script 20/15/2016 and 2017 ecmascript 2015 which is basically yes six you also have
this led keyword but in case you are not familiar with it let me explain how it works so I’m going to
define a function let's call it do something it doesn't really matter here I’m going to define A4 block so far
we said it to 0 and as long as I is less than five let’s increment it here we have a block and then log it on
the console now finally at the end of this function I’m going to log this I one more time but with the label
finally and then I’m going to call this function here so I need to terminal I’m going to compile this file
main dot JS and also at the same time run it with note main dot JS note that the value of I at the end is 5
so this is the issue we have when declaring A variable using the var keyword so we have declared I here
inside this four block but is also meaningful and available outside the four block now if you have worked
with languages like C or Java you know that we don’t have this concept in those languages in JavaScript a
variable declared with the var keyword is scoped to the nearest function so in this case the nearest
function is do something so once we declare I inside this four block it’s available anywhere in this
function now let’s see what happens when we declare this variable using the left keyword so let now
look we immediately got a red underline here whichh indicates a compilation error and this is one of the
beauties of TypeScript when you are writing TypeScript code you can catch these errors at compile time
before you run your application before you deploy it now let's hover our mouse here so this is the error
cannot find name I so now I is sculpted to the nearest block instead of nearest function and this is the
proper way to declare variables which prevents a lot of Issues later down the road now I want to clarify
something let me see if this file how can the terminal first I’m going to remove main dot JS now I’m going
to recompile are made ATS OK we got our error here cannot find name I however if you look at the files
in this folder we do have main dot JS so even though we have a compilation error TypeScript compiler
still generated main node JS let’s have a look at the content of this file so this is the code that is
generated so by default TypeScript compiler compiles our TypeScript code to ES5 or ecmascript 5 which
is the older version of JavaScript that is supported by all browsers out there now there we don’t have the
left keyword so that’s why our compile code now uses the var keyword and this is perfectly valid
JavaScript code so I can go into terminal and simply run this code and get the same output as before So
what I want to clarify here is the TypeScript compiler reports these errors but still generates valid
JavaScript code so here's ’he take away for this lecture from now on anywhere you want to declare a
variable we use the let keyword once again this does not stop the compilation step but at least we can
catch the issues earlier during the compile time next we’re going to look at different types we have in
TypeScript in this lecture I’m going to show you a different types we have In TypeScript so let me start by
declaring a variable called count and set it to 5 now if I set this to let’s say a character or a string like hey
build that I immediately get a compilation error here telling me that this a string or a character is not
assignable to type number now we can perfectly do this in JavaScript because in JavaScript we can
change the type of variables on the fly but in TypeScript we get a compilation error now once again I
want to clarify that we can perfectly compile this using TypeScript compiler and we will get valid
JavaScript code so if I go to terminal and type TypeScript compiler main dot TTS outlook this is our main
dot JS so we have this count variable and we have changed its value we can perfectly execute this no
problem however code like this is very likely that it’s going to break some point in the future because
chances are we’re going to use this count variable inside a four block so our program is going to break at
runtime you don’t want this to happen right that’s one of the reasons It’s better to write the same code
in TypeScript so at least we can get a warning during the compilation step now if you hover your mouse
over this count variable look at the tool tip you can see a colon and number after a discount so this
indicates the type of count variable in our program so here TypeScript compiler inferred that the type of
this variable should be a number because we set it to #5 now what if I declare A variable without
initializing let’s look at this type it's type Is now any and that’s exactly like the variables would declare in
JavaScript so I can set A to 1 then I can change the value to true and then set it to your string even
TypeScript doesn’t complain about this so what’s the solution if you don’t know the value of a variable
ahead of time that’s when we use type annotations so here we add: and after that we set the type of
this variable like number and then look on the 3rd and 4th lines you got compilation errors now in
TypeScript you have a few different types so we have number which can include any integer or floating
point numbers we have booleans which can be true or false we have strings we have any that you saw
earlier we have arrays so let's say we want to declare an array of numbers you would use number square
brackets now we can optionally initialize this to an array like this or we can declare and any array and
with this you can set this to an array with this values one true A and false of course it’s not a good
practice we want to avoid this but I’m telling you what is possible with TypeScript now we also have
another type that I absolutely love and that’s ina so let's say you're working with a group of related
constants like colors so in plain old orphaning of JavaScript we would define constant colors like this so
color red we can set this to 0 constant color green we set this to one and constant color blue set to two
this is a little bit verbose in a lot of object oriented languages we have this concept called enum so we
can put all these related constants in a container so in TypeScript we can declare an enum like this you
know all lowercase give you the name like color a curly braces and here we set the values so red green
and blue then we can declare a variable like background color and set it to color dot now look we have
intellisense here so this tooltip you see here allows us to complete this code without remembering all
the details this is one of the things I love about TypeScript so let’s set the background color to color dot
red in terms of the values the first element here automatically gets the value of 0 each subsequent
element yes an incremented value so we don’t have to explicitly set this but as a best practice it’s better
to do so because chances are sometime in the future someone may come here and add a new color here
like purple and then purple would automatically become two and the value of blue would change to
three so this may break parts of our application so let me revert this by explicitly setting the values if
somebody adds a new color here like purple then it will not change the value of blue now let me show
you something let’s compile this code and see how we get enum in JavaScript so touch script compiler
main dot TS look at this piece of code here this is how we can implement the concept of enums in
JavaScript you can see it's very complicated now compare this with how we declare it an enum here it's
much cleaner so the more you work with TypeScript the more you’re gonna love this language in this
lecture I’m going to show you the concept of type assertions in TypeScript so I’m going to start by
declaring A variable like message and setting it to your now here we can type message dot and look we
get this beautiful intellisense and in this tooltip we can see all the things we can do with a string so all
these items with this purple icons are functions for example we have this function called endswith you
can call this and see if this message ends let’s say with C and this returns a boolean so we can store the
result in another variable like and with C however sometimes TypeScript may be a little bit confused
about the type of a variable for example I’m going to remove this initialization here and initialize this
variable on the second line ABC now look at the type of this message variable it's Anna because by
default when we don’t set a value the type is ending but the problem here is that if I delete this and
type. Look we don’t get that intellisense anymore because ends with is something that we can do with a
string not with an object of type So what should we do in this case we need to explicitly tell TypeScript
compiler that this message variable is actually a string and this is what we call type assertions now how
do we do type assertions there are two ways one way is to prefix this variable with angle brackets and
here we put the type like string now we need to enclose both these parts in parentheses like this then if
you press. We get our beautiful intellisense with all the functions or methods available on string objects
there is also another way to do type assertion so let's change the name of this variable to alternative
way and here instead of angle brackets use message as string or exactly the same the approach shows
it’s purely your personal preference but the first approach is what you see more and a lot of tutorials and
code bases out there I just want to clarify something here this type assertion does not change the type
of this variable at runtime in fact it’s not going to restructure that object in memory it’s purely a way to
tell TypeScript compiler about the type of a variable so we can access the intellisense another concept
you need to know when using TypeScript to build angular applications is the concept of arrow functions
in JavaScript we can’t declare a function like this let log we set this to a function this function takes
message object and simply locked it on the console like this now in TypeScript there is a shorter way to
define this function so let's call it the other one do log Now we don’t need the function keyword
anymore you can simply add the parameters in this case message then we add this arrow and this is
what we call this an arrow function finally the code block so console that log message now if our
function has only one line you can even exclude these curly braces so you can make this code a little bit
shorter and cleaner like this I worked with C# and I’ve seen this before and C# we call this a Lambda
expression in TypeScript we call it an error function exactly the same if you have one parameter here you
can even exclude the parenthesis but I personally don’t like this because I think it makes the code a little
bit less readable so I always like to put my parentheses here to indicate to the reader of this code that
these are the parameters now what if we don’t have any parameters we just add empty parentheses and
of course here you don't have the message so if you have not seen this before get used to it it’s a really
nice and clean way to define functions all right now let’s see how we can use custom types in TypeScript
so I’m going to store it by declaring a function like draw point so this function takes an X&AY and simply
draws it on the screen now we don't want to worry about the actual drawing algorithm we just want to
focus on the signature of this function this function is not too bad here we have only two parameters but
sometimes when working with more complex concepts you may end up with a function that has so many
parameters like this this is really really bad and it’s something you should avoid at all times in those
situations it’s very likely that a group of these parameters maybe all of them belong to a single concept
as an example think of a car a car has so many different properties we don't want to pass all those
properties to function like drive car instead you want to encapsulate them inside an object and only pass
that one object here so in this example instead of passing X&Y here it’s better to pass a point object and
then we can call this function like this draw point we give it a next with two properties X&Y so now our
function has a cleaner syntax however there is a problem with this implementation instead of a point
object I can pass a person object that has a name property and nowhere here we’re getting a compile
time error but we know that this code is gonna break at runtime because the algorithm in our draw
point function is expecting X&Y properties so what’s the solution well let me revert this back OK we’ve
got excellent wine so there are two solutions to solve this problem one way is to use what we call inline
annotation so just like we can annotate this parameter with the type like number we can annotate it
with a custom type or custom object so here we add curly braces to indicate an object this object is
going to have a property called X which is a number also another property called why which is again a
number so this is what we call inline annotation it works fine for simple cases but the problem with this
as you can see is that this is a little bit verbose also chances are somewhere else we might have another
function that expects A pointer object we don’t want to repeat this object literal in multiple places so in
those cases a better approach is to use an interface if you work with object oriented program languages
like C# and Java you know the concept of interfaces you have the same concept in TypeScript if you have
never worked with interfaces let me show you how they work so on the top I define an interface I’m
going to call this point garlic races then I add X there’s a number why is the number so with this interface
I’m defining the shape of an object then I can simplify this declaration and set the type of this parameter
to point this is much cleaner and we can also reuse this in multiple places just one thing note the naming
convention I have used here so because I’m introducing a custom type I’ve used Pascal naming
convention so the first letter of every word in the name of the interface should be capitalized so here we
have uppercase P other lowercase P okay so when using interfaces always use a skull naming convention
so in the last lecture we used an interface to define the shape of a point object but there is a problem
with this implementation in object oriented programming languages we have this concept called
cohesion which basically means things that are related should be part of one unit they should go
together this is what we call cohesion now back to this example on the top we have used an interface to
define the shape of a point object below that we have a standalone function and this is where we have
violated the cohesion principle so the concept of drawing a point is highly related to the structure of a
point It should not be a separate function now if you’re going to build a utility library for working with
points chances are you’re going to create another function like get distance it calculates the distance
between two points so point a of time point and point B of type point and this goes to this code block
again we have violated the cohesion principle we have two functions hanging in the air separate from
the point object since these concepts are highly related they should be part of 1 unit in object oriented
languages we call that unit class so a class groups properties and functions that are highly related now in
this implementation unfortunately we cannot move these two functions inside our interface because
interfaces are purely for declarations they cannot include any implementation in other words we cannot
have algorithm for calculating the distance between two points or drawing a point inside this interface
what we can do instead is to add function here function declaration so we're going to have a draw
function that takes no parameters and returns void which means it doesn’t return anything now you
might be asking why don’t we have this point parameter here because if all these members XY and draw
are part of one unit we don’t need to pass X&Y as parameters the draw function this function can
directly access these properties X&Y the same unit so we don’t need this parameter here now in
interfaces as I said we cannot have implementation can only have a signature of a function so with this
interface you’re telling TypeScript compiler that our point objects should have two properties X&Y and a
function called draw the implementation of that is somewhere else So what should we do now to apply
the cohesion principle here we need to use a class instead of an interface so on the top I’m going to
change the type class and here I’m going to replace this, with; so our point class has three members the
first two members are what we call fields that we use for storing data the third member is a function
here in this class we can have the actual implementation of this draw function so we can simply define it
like this draw and then Add all that logic or drawing a point a similarly can have another function yet
distance it returns the distance between this point and another point like this again all that logic will end
up here now with this restructuring you can see that everything about the point is in one unit 1 class so
we have the coordinate which includes XY and two functions draw and get distance I mean object
oriented programming terms you’re referring to these members as fields and to these functions as
methods so when a function is part of a class we call it a method all right now with this new
implementation you don't want these two functions hanging in there so delete this is a much better
structure also you're not gonna call drop point like this anymore so here’s our point class in the next
lecture I’m going to show you how to create an object of this type and call the draw method alright so
here's our class now let's declare A variable of this type so let me point you have type right and then you
can type point dot look we have this beautiful intellisense we have two methods draw and get distance
and two fields X&Y now in TypeScript we also have a concept called property which is different from a
field but a lot of people use these terms interchangeably later in this section you're going to learn the
difference between fields and properties now if you want to call the draw method simply call it like this
so this draw method is now part of the concept of a point it’s not a function hanging in the air polluting
the global namespace now for this demo I’m going to add a simple console dot log here and displayed
the coordinate of this point so X here I want to add the X field but we cannot use it like this you need to
prefix it with this dot so that refers to this field in this class then I’m going to add Y is once again this dot
Y others compliant run this program and see what happens so TSC what should we type here main dotts
and we can shortcut by adding this pipe here I’ve known then main JS OK you got a runtime error cannot
read property draw of undefined but this is the problem when we call this draw method this point object
was undefined because here unlike the basic types we have in TypeScript like numbers strings booleans
we’re dealing with a custom type when defining an object of a custom type we need to explicitly allocate
memory to it how do we do that well here where we declare the point object or the point variable
initialize it using the new operator so this object is a new point and here we add parentheses this is the
syntax you can see that we have repeated this point here twice so we can make this code a little bit
cleaner by removing this type annotation because TypeScript compiler can infer from this assignment
here that the type of this object is a point object and let's verify that so look you’re working with a point
object now one more time save so back in the terminal subscript compiler main dot TS and node main
dot JS OK we didn’t get an error but you can see that this X&Y fields don’t have a value because by
default there are undefined so we can get back here and set the point that X2 let’s say one and point out
why to two am I going to terminal so instead of this pipe operator we need to use double & on Mac I
don’t know the windows equivalent so with this we can combine multiple commands so node main dot
JS all right beautiful X is one and Y is 2 so this is how we use the classes that we defined in our programs I
want to highlight something here is point here as a class at this point here is an object an object is an
instance of a class as a metaphor think of the concept of a human human could be a class but maybe
create instances of this class like John Bob Mary these are all objects so that’s the difference between a
class and an object next we’re going to look at constructors alright so I’ve simplified the code from the
last lecture I simply removed the method get distance because we’re not going to use it later in this
section so here on the top we’ll define a point class and then below that we initialize a point object this
code is a little bit verbose because we have three lines to create a point object and put it in a valid state
what if this point object had if you had a properties that we had to initialize like this maybe a few more
here is there a cleaner way absolutely so let me delete this first in object oriented programming
languages we have this concept called constructor so every class can have a constructor which is
basically a method that is called when we create an instance of that class so let me show you how it
works in the class I’m going to add the method the name of this method is constructor this is a reserved
keyword in TypeScript now this method can have parameters so X it’s just a number and why which is
also a number and then here in this method we can initialize these fields So what should we write here
this dot X we set it to this X argument that we get here and similarly this that why set it to now look
we've got a compilation error here because when creating a new point object we need to supply these
values at the arrow supply parameters do not match any signature of call target so here we need to
supply the values for X&Y one and two and with this we can simplify this code and get rid of these two
extra lines here's the end result now what if somewhere else in our program we don't know the initial
coordinate of a point in other words what if I want to create a pointer object without setting those
values is that possible yes absolutely but it’s a little bit different from how you have seen that in other
languages like C# and Java in C# we can have multiple constructors in TypeScript we can’t so the solution
for this is to make these parameters optional so here after X I add a question mark and that makes eggs
optional and similarly why should be optional as well because once you make a parameter optional all
the other parameters on the right side of that parameter should also be optional this is a rule by
TypeScript and a lot of other program languages so now look we don't have a compilation error when
creating a point object without initial values all right so here I’ve created a point object with an initial
coordinate now what in our program you want to have this rule such that when we initialize a point
object we should not be able to change the X or Y values with this implementation you can always come
here and set point X to a different value how can we avoid this sometimes we need this feature in our
programs because it will make them more predictable it reduces the chance for bugs so how should we
prevent the coordinates of this point object to change after its initialize well in object oriented languages
we have this concept called access modifiers access modifier is basically a keyword that we can apply to
a member of a class to control its access from the outside so in TypeScript we have three access
modifiers public private and protected public and private are the most common and by default all
members are public let me show you what I so here in our point class we have three members right we
have two fields and one method so let me create a pointer object and type point dot look these are the
members of the class and because they are all public we can access them here that’s why we can see
them in the intellisense however I can go here and prefix this build with the private keyword no once we
create this pointer object if I type point dot look X is not in the list it’s not accessible it’s private so if we
try to set point dot X to three look we have a compilation error in TypeScript it says property X is private
and only accessible within class point now with this technique I can go here and applied to private
keyword on the wide field as well and now once I initialize a point object I can no longer change its
coordinates I can only call the draw method OK so This is why we use access modifiers to control access
to certain members of the class from the outside you can apply these access modifiers on fields
properties and methods now why default if you don't set an access modifier is assumed to be public so
here the draw method as you know is public can also add the public keyword here but this is redundant
it’s just making my code noisy so you don't really need to add this it's better to keep your code short and
clean and use the private access modifier only when you need to next I’m going to show you one of my
favorite features of TypeScript around access modifiers as you write code with TypeScript you’ll see
constructors that follow a pattern like what you see here so here we have two parameters in our
constructor and we use these two parameters to initialize built in this class the code looks a little bit
redundant this dot X = X and this dot y = y TypeScript as a fantastic feature that helps you achieve the
same thing with less code so here we can delete these two fields here and in our constructor We can
prefix our parameters with an access modifier so here I want to have two private fields X&Y I can simply
prefix this with the private keyword like this so TypeScript compiler will generate these fields for us also
you don’t need these ugly repetitive assignments either so if you prefix A constructor parameter with an
access modifier with a private or public TypeScript compiler will generate a fill with the exact same name
and it would also initialize that field with the value of this argument it’s one of my favorite features and
you’re gonna see that a lot in this course that clarify something before we finish this lecture in this case
our fills were private but if they were public we would use the public keyword here so this means when
we create a pointer object you can access the X field OK so I’m going to revert this back but the private.

You might also like