Step 3: Basics of variables
Like most programming languages, we use variables to store values, such as a string, Boolean, number, or expression. In TS, we can define a variable using var
, let
, and const
. There are some issues that arise when we use var
. For example, a variable declared with var
inside a function is function-scoped but global-scoped when declared outside a function. This can lead to errors in the JavaScript code.
The keyword let
solves this problem by setting the variable’s lifespan at the block where it was declared. Similarly, const
solves the same problem as let
, but it can only be initialized once when it is declared. Typescript will make sure no value can be set.
Variables in Typescript follow similar syntactic rules as many other programming languages.
- They can be comprised of lower and uppercase letters of the alphabet
- They cannot begin with a digit
- They can include special characters, such as
$
or @
.
Step 4: Commenting in TypeScript
Comments in TS use the same syntax as Javascript Double slash for single-line comments Slash stars to open a block of comments Star slash to close a block of comments
Typescript introduces a special syntax. If you add /*!
, Typescript will keep the comment while transforming into Javascript. This enables you to keep copyright at the top of a TS file that needs to be generated in JS.
let x = 1; // This is a single line comment
/* This can be spread on
multiple
lines */
let y = 2;
Step 5: Type Inference
Type Inference is what the compiler uses to determine different types. It is smart enough to figure out types from their values. That way, you won’t have to specify your types in your code. This a powerful feature of Typescript that allows you to manipulate types and combine them.
The Typescript inference features can infer types in the following scenarios:
- When variables are declared and initialized
- When default values are set as parameters
- When the function return types are determined
Step 6: Functions
Typescript does not make any major changes to the function-scoped core of Javascript. However, Typescript does enhance functions with strong signatures we can use to define parameters and return types.
We declare a function using the function
keyword. You can also use the fat arrow
to make a function without the keyword. This does not change with Typescript. We can use Typescript types for function arguments. We use a colon to do so. Take a look at an example:
function functionWithParameters(arg1: string, arg2: number){}
Typescript functions fall into two categories: function expressions or function declarations. A function declaration is when a function is defined by not assigning it to a variable while a function expression is assigned to a variable.
In Typescript, you can specify the type of a function with this
keyword. To do so, you use the this
followed by a colon, followed by the type of the function signature.
Step 7: Mapped Type
This functionality enables you to create a new type from an existing one. For example, you could have an existing interface keep all the same members but change into read-only or optional. Before the mapped type, we would have to create an extra interface to reflect the final state we want, which can pollute the code and lead to issues.
And without the mapped type, every interface would require a separate function, so things can get out of control quickly. Thanks to the custom logic of a mapped type in Typescript, we don’t have to deal with those issues.
There are different mapping functions in Typescript: partial, nullable, pick, omit, record, extract, exclude, and ReturnType.
Step 8: Objects and OOP
Typescript supports object-oriented programming and adds new features to improve upon Javascript’s OOP functionality. Typescript supports the use of classes by using the class
keyword. Think of this like a template of objects. Let’s take a look at an example:
class class_Name{
field;
method;
}
This will generate the following JavaScript code:
// Generated by typescript 1.8.10
var Person = (function () {
function Person() {
}
return Person;
}());
Typescript introduced new ways of using objects. There are many different object types in Typescript: Object
, object
, and {object}
. Typescript can create an object using curly brackets, and you must define its members at initialization. It’s a quicker way to organize your data, and you do not need a name since it’s not a structural language.
Step 9: Type Checking and Assertions
Let’s look at how we can check that our variable has the right type. Here are the two most common approaches.
Instanceof
This operator can check for custom types not defined by Javascript. Below, we first write a custom type, make an instance of it, and check that it is indeed the right variable.
class Dog{
name: string;
constructor(data: string) {
this.name = data;
}
}
let dog = new dog('Rover')
if(dog instanceof Dog){
console.log(`${dog.name} is a dog`)
}
Typeof
This operator can check for basic datatypes. Below, we make a string variable, use the typeof command to check it against another variable and then print the result.
let myObject = { name: "test" };
let myOtherObject: typeof myObject; // Borrow type of the "myObject"
myOtherObject = { name: "test2" };
type TypeFromTypeOf = typeof myOtherObject; // Borrow
Sometimes, we need to cast our variables to a datatype, commonly when you are using a general type and need to make it more concrete. There are a few different ways to do this. Let’s discuss two popular approaches.
As
Keyword
Use the as keyword after the name of the variable and end it with the desired datatype.
let str: any = 'This is a String'
let strLength = (str as string).length
< >
Operator
We can also cast our variables by using the < >
operator. This has the same effect on our code but implements a simpler syntax.
let str: any = 'This is a String'
let strLength = (<string>str).length
Conclusion
Now you have a basic sense of how to use TypeScript, and you can see how it will make your Javascript code less prone to bugs. You’re ready to move on to more advanced concepts. Since Typescript is gaining more momentum in the web dev world, there are tons of great resources out there for those who want to get started and revamp their front-end career.
The most robust course for those looking to master Typescript is Learn TypeScript: The Complete Course for Beginners by Patrick Desjardins, who is a Senior Netflix engineer and former Senior Microsoft engineer with over 20 years of professional development experience. This interactive, hands-on course walks from the complete beginner to the advanced concepts of Typescript, like iterators, manipulating objects, and more. It’s a one-stop-shop for any frontend developer who wants to keep up with this must-know language.