You have already taken your first step in the right direction by opening this article to learn TypeScript. Typescript’s importance and value is realized when working on medium to large-scale application with 2-3+ people working on a single codebase. We will discuss things from the perspective of Functional Programming, which means no Class
, OOPs
, etc., and the difficulty level of this article will be “Very Easy”.
Types and Interfaces
These two are the basic building blocks that you will use on a daily basis, the objective of both are the same, but the Interfaces carry some extra functionalities.
So let’s define our first Type
let fullName: string = "Jon Snow";
And that’s it, you just created your first Type
just by adding : string
after variable the name.
But this is not how commonly Typescript is used even though technically it is right. Because of something called Type Inference, even if you write the above code like this
Its Type
is automatically inferred from "Jon Snow"
that is string
, you will get to see the magic of Typescript when you try to reassign fullName
variable to anything other than the datatype string
I know you might be thinking, “So, what’s the big deal? It just throws an error for a simple thing”, well it is a big deal, and you will also realize that by the end of the article, and trust me you would rather want 100 bugs in development than in production.
Built-in Interfaces
For the default data types of JavaScript, there are some built-in interfaces
such as Array
, Record (Object)
, Date
, etc.
Now let’s take a simple, interesting, yet powerful example to learn how to use them in your code. We will declare an Array
of Person’s Object
, that consists of name, age and gender.
But first, we will define the Type
of person’s Object
type Person = {
name: string;
age: number;
gender: string;
};
And now lets declare a variable arrayOfPersons
, now there are two ways you can do that
let arrayOfPersons : Person[] = []
// or
let arrayOfPersons : Array<Person> = []
the result of both is the same, now lets add some object into the array.
For types
and interfaces
you should follow the naming convention of Pascal Case, which is what most people follow
Normally if you are using JavaScript, you will get suggestions of the available methods and properties of Array
, but since we are using TypeScript we get type checking for the value you are about to add to the array
.
Not only that but it also tells you what kind of data is accepted in this particular object and will throw error till the required Type
is satisfied
Isn’t this great !?! This way you don’t have to wait till you get undefined
, null
, or unexpected output in the browser, your IDE tells you beforehand.
You can make properties optional by adding ?
like this
type Person = {
name: string;
age: number;
gender?: string;
};
Typed Functions
Having strongly typed
functions saves a lot of time during development and keeps everyone working on the project sane without introducing unexpected errors because of inputs with wrong types
To define type
for a function there are two ways depending on which keyword you are using,
For type
the syntax is
type typeName = (arg1: arg1Type, arg2: arg2Type) ⇒ returnType
And for interface the syntax is
interface typeName {
(arg1: arg1Type, arg2: arg2Type): returnType;
}
Let’s write a function that prints the information of a person from an array passed as a parameter
This will be its type
// typeName arg1: arg1Type arg2: arg2Type => returnType
type PrintInfo = (array: Array<Person>, index: number) => void;
// or
// typeName
interface PrintInfo {
// arg1: arg1Type arg2: arg2Type : returnType
(array: Array<Person>, index: number) : void
}
And this will be our function
const printInfo: PrintInfo = (array, index) => {
const person = array[index];
const message = `${person.name}'s age and gender is ${person.age} and ${person.gender} respectively`;
console.log(message);
};
// or
const printInfo: printInfo = function (array, index) {
const person = array[index];
const message = `${person.name}'s age and gender is ${person.age} and ${person.gender} respectively`;
console.log(message);
};
just like before, if you pass the values with incorrect types it will throw error
And this part is so helpful as it doesn’t just checks if the correct values are passed but also provides documentation to the function.
For someone just starting to learn or implement Typescript it will feel like a obstacle in your way with lots of type error, one might even fell that it is slowing him down but as the project gets bigger typescript you will thank yourself for using typescript making it through he hurdles.