Introduction
TypeScript is built on top of JavaScript. In simple terms, it is a more powerful version of JavaScript. It is a superset of JavaScript language.
All the browsers support JavaScript language, not TypeScript. So, We need to convert TypeScript code into JavaScript code.
TypeScript compiler helps us here. It converts the TypeScript code into JavaScript code.
One of the important features of TypeScript is static-typed language. It means a type of variable is known at compile time, we don't need to execute code to check the error.
JavaScript is a dynamic-typed language, which means we can't know errors until we execute code. The type of variables is associated with run time.
Set-up environment
I'm going to use the VS Code editor on a windows laptop for this demo.
Let's install the TypeScript compiler first.
Open the code editor's terminal and type the following command:
npm install -g typescript
To check the compiler has been installed successfully You can check the compiler version by this command:
tsc - v.
It will display the compilar version if it has been installed.
Hope you have installed the compiler successfully.
Get Started
Let's create our first TypeScript script file.
First, create a TS_Demo
folder and open it with the vs code editor.
Create a file named index.ts
within this folder. Note that the file extension name is .ts
In the file, type console.log("Hello World!")
.
index.ts
console.log("Hello World!");
Now, we will compile index.ts
file with the TypeScript compiler to convert TypeScript code into JavaScript code.
Open terminal and type: tsc index.ts
The compiler will generate a JavaScript file (index.js
) corresponding to the TypeScript file(index.ts
).
You can find the JavaScript file(index.js
) in your current directory.
index.js
console.log("Hello World!");
Configuring the compilar
We can configure compiler settings with the help of tsconfig.json
file.
To generate tsconfig.json
file, we need to execute tsc --init
command.
Open tsconfig.json
file. You will find lots of settings in JSON format which you don't need to remember. You will get familiar with them according to your project requirements.
tsconfig.josn
file lets you
Choose which version of ECMAScript you want to use - ES205, ES2016.
if you want to use
strict mode
or not.Choose the path for output js files.
choose many more features.
You can read more about tsconfig.json
file here.
Data Types
TypeScript supports all the data types that are present in JavaScript, plus it has also introduced a few more.
The primitives:
The followings are basic data types that you are pretty familiar with.
string
number
boolean
Let's understand them by examples.
//string
let name : string ; // declare a string variable
name = 12; // error, can't assing number to string type
name = "Jack";
//number
let age : number;// declare a number variable
age = "21"; // error, can't assign string to number type
age = 21;
// boolean
let isAdult: boolean;// declare a bool variable
isAdult = 12; //Error, can't assign number to boolean type
isAdult = "no"; //Error, Type string is not assignable to type boolean
isAdult = true;
Type Assignment
TypeScript assigns types in two ways.
Explicit
Implicit
//Explicit
//We annotate variable with a type at the time of declaring variable
let name : string = "Jhon Doe";
//Implicit
// TypeScript guess the type based on Assigned value
let name = "Jhon Doe";
name = 12; // Error, type number is not assignable to type string
Type Inference
When we declare a variable in implicit way, TypeScript guess the type of the variable. This process is called type inference.
The special type
TypeScript has introduced a few special data types:
any
unknown
never
enum
tuple
Let's understand them by examples one by one.
- any
A variable that is annotated with any
type can be assigned any type of value. But there is a caveat here, with this type we lose all the features that TypeScript provides like type checking, code hints, and auto-complete.
In simple words, TypeScript closes its eyes and stops checking types. You are free to assign any type of data.
let x:any;
x = 1;
x = "Hello";
x = {id: 1};
We should avoid the use of any
as much as possible.
- unknown
unknown
it is stricter and safer than any
.
Both any
and unknown
can be assigned any type of value. But the unknown
is different in a few ways.
unknown
is assigned only tounknown
andany
types.We have to use type assertion if we want to assign
unknown
to other typesunknown
doesn't allow us to perform any operations like calling methods.
let x : unknown = "abc";
let y : string = "Jhon";
let z : unknown = 12;
z = x; // ok
y = x; // Type 'unknown' is not assignable to type 'string'
y = x as string; // type assertion
x.toUpperCase();//Error, 'x' is of type 'unknown'
- never
the never
type represents the type of values that never occur.
Think of it as an empty type or no type.
TypeScript compiler assigns a type to every variable and property. If the compiler is unable to assign a type, then that variable is considered never
type.
If a function has an infinite loop within it or it throws an error, then its return type is never
.
Example:
function foo ():never {
while(true) {} // infinite loop
}
function () : never {
throw Error('my error'); // throw an error
}
Variables are also assigned the type never
when narrowed by conditions that can never be true.
Example:
function format(value: string | number) {
if (typeof value === 'string') {
return value.trim(); // value is type of string
} else {
return value.toFixed(2); // value is type of number
}
// the value is not a string or number.
// "value" can't occur here, so it's type "never"
// So its type is "never"
console.log(value); // unreachable code. compilar can't assign any type.
}
- enums
The enums
type is a set of related constants. It makes it easier to define a set of constant variables that takes a fixed set of values.
TypeScript provides both numeric and string-based enums.
By default, each enum variable has a numeric value which starts from 0 and auto-increment for the rest variables just like an array index.
However, we can change the starting value, we could start from 1 instead of 0.
// numeric enums
enum Direction {
Up = 1, // by default it starts from 0 if we don't assign any value
Down, // 2
Left, //3
Right // 4
}
// string-based enums
enum Direction {
Up = "up",
Down = "down",
Left = "left",
Right= "right"
}
let myDirection: Direction ; // Declare an enums Direction type variable.
- tuple
The tuple is a fixed-length array, and each element in the array has a type associated with it.
We can use a tuple to store related variables like key-value pairs, or RGB values.
Note that in a tuple order of elements matters. Elements should be stored in the same order as their types.
Let's understand tuples with examples.
// element should be stored in the order of [number, string , boolean]
let myTuple : [number, string, boolean];
myTuple = [1, 'Hello', true];
// wrong order of elements
myTuple = ['Hello', 1, true]; // Error, can't assign string to number type
let RGB : [number, number, number] = [255, 0, 0];
//we can de-structure a tuple just like an array
let [red, green, blue] = RGB;
Summary
We have learned about some basics of TypeScript. We learned how to :
Install TypeScript compilar
Set up environment
use primitive datatypes like - number, string, boolean
use special datatypes like - any, never, unknown, enum, tuple
I hope you find this article helpful.
In the next article, I will write about functions and objects in TypeScript.