JavaScript is a language that has a weak typing, this means that the variables are declared without a type and depending on the value assigned to it is the type of data that the variable assumes. We can modify, operate and compare the values between them without having to do a previous conversion.
In the following example we can see how we change the data type without any type of conversion:
1 2let name = "Learning Javascript" 3console.log(typeof name) 4// "string" 5 6name = 33 7console.log(typeof name) 8// "number"
Typescript is a programming language that adds new features to Javascript, this is known as a superset. A superset is written based on another programming language, applying improvements to the original language. That is why Typescript was written about JavaScript: to add new features that you will see later.
Typescript is the solution to many of the JavaScript problems, it is designed for the development of robust applications, implementing features in a language that allow us to develop more advanced tools for application development.
Static typing defines that:
Variables have only one data type
The values assigned to the variables must have the same type as the variable.
The following example is declaring the variable message
of type string
. The values must have the same data type as the variable, for this reason the string Learning Typescript
is assigned
1let message: string; 2message: 'Learning Typescript';
Variables can have different types of values, below you can see how we can define each type using TypeScript:
1let isExist:boolean = true
1let message:string = "Learning TypeScript"
1let age:number = 33
1let isNotExist:null = null
1let arrayNumber:Array<number> = [1, 2, 3, 4] 2let arrayNumber:Array<string> = ["one", "two", "three", "four"]
1let arraytupla: = [number, string, number] 2arraytupla = [23, 'Hello World', true]
1let notDataType:void = undefined
1enum Animals {cat, lion, dog, cow, monkey} 2let c: Animals = Animals.cat;
1let wherever: any = 14; 2wherever = "people";
As in any other object-oriented programming language, classes in TypeScript have fields, constructors, properties, and functions. Classes act as containers that encapsulate code to be consumed in an easier way.
When defining a class we use the word class
and close with curly brackets {}
, as well as in c# and java, and then we define inside our fields, constructors, properties and functions.
1 2class User { 3 # fields 4 private name: string; 5 private lastName: string; 6 7 # Constructor 8 constructor(name: string, lastName: string){ 9 this.name = name; 10 this.lastName = lastName; 11 } 12 13 # Properties 14 get getName(): string { 15 return this.name; 16 } 17 18 set setName(value : string): string { 19 if(value === undefined) throw 'Enter a valid value'; 20 this.name = value; 21 } 22 23 #Functions 24 fullName(){ 25 return this.name + ' ' + this.lastName 26 } 27} 28 29const newUser = new User('Juanin','JanJarri'); 30console.log('The new user is:', newUser.fullName()) 31
In the previous example a constructor ()
method is defined that receives the parameters name: String, lastName: String
, these parameters are assigned to the internal values of the class using the this
method to reference them.
In addition, the Properties
allow us to obtain and assign data from variables or internal methods of the class. In the example, the setName ()
method allows assigning the value received as a parameter to the internal property called name
. The getName ()
method allows obtaining the value of the internal property 'name'.
The Functions
allow us to execute functions or internal methods of the class, in the example theb fullName ()
method returns the union of the internal properties name
plus lastName
.
To create an instance of the User
class we define the following constantconst newUser = new User ('Juanin', 'JanJarri');
In these lines of code you can see that when creating this instance the parameters are sent ' Juanin ',' JanJarri'
to the constructor to initialize the class with those values.
Sometimes called signatures, it is the mechanism that Typescript uses to define types in classes. They allow you to define the structure or the most complex type of objects.
The way an interface is used is very similar to how a class is defined, but only attributes and methods and their implementation are declared.
Like simple variable types, these objects will also need to follow a set of rules that you create. This can help you write code with more confidence and less chance of error.
In the following example we define an interface called Lakes
:
1interface Lakes { 2 name: string, 3 area: number, 4 length: number, 5 depth: number, 6 isFreshwater: boolean, 7 countries: string[] 8}
The interface Lakes
contains the type of each property that we are going to use when creating our objects. Next we will create a new firstLake
object that will inherit the properties of the Lakes
interface.
1let firstLake: Lakes = { 2 name: 'Caspian Sea', 3 length: 1199, 4 depth: 1025, 5 area: 371000, 6 isFreshwater: false, 7 countries: ['Kazakhstan', 'Russia', 'Turkmenistan', 'Azerbaijan', 'Iran'] 8}
As you can see, the order in which you assign a value to these properties does not matter. However, you cannot omit a value. You must assign a value to each property to avoid errors when compiling the code.
In this way, Typescript ensures that none of the required values are lost by mistake.
Sometimes you may need a property only for some specific objects.
For example, suppose you want to add a property to specify the months that a lake freezes. If you add the property directly to the interface, as we have done so far, you will get an error for other lakes that are not frozen and therefore do not have the frozen
property. Similarly, if you add that property to lakes that are frozen but not in the interface declaration, you will still get an error.
In such cases, you can add a question mark ?
After a property name to make it optional in the interface declaration. This way, you won't get an error for missing properties or unknown properties. The following example redefines the Lakes
interface but the area
property remains optional.
1interface Lakes { 2 name: string, 3 area?: number, 4 length: number, 5 depth: number, 6 isFreshwater: boolean, 7 countries: string[] 8}
This lesson introduces all the data types that are available in Typescript. We learned how assigning a different type of value to a variable will give you errors in Typescript. This check will help you avoid many errors when working on large and robust applications.