To read this blog you must understand JavaScript first. If you are a beginner and yet don’t know JavaScript you can explore other JavaScript blogs on our website. TypeScript is a superset of JavaScript, which means it includes all the features of JavaScript and extends it with static typing. Static typing allows you to define the types of variables and function parameters, and return values explicitly, which helps catch errors early in the development process and enhances code quality.
Setting up typescript development environment
Before getting started with TypeScript make sure you have a development environment set up for it. First install Node and Vs Code Editor. You can install and manage node versions using nvm . Once installed follow along with me. Run the following code to create a starter project My-typescript-project
mkdir My-typescript-project
cd My-typescript-project
npm init // keep entering until finishes
Now open the folder My-typescript-project inside vs code editor. To work with TypeScript, you typically use a build step to compile TypeScript files ( .ts
) into JavaScript files (.js
). Then, you can run the compiled JavaScript code.
Install TypeScript Globally:
First, make sure you have TypeScript installed in your project. You can install it using npm or yarn, then you can check for typescript version.
npm install -g typescript
tsc --version
Create a build command to compile Typescript files:
Add a build command to your start
script that compiles TypeScript files into JavaScript using the tsc
(TypeScript compiler) command. In the root of your project, create a tsconfig.json
file, which is a configuration file for TypeScript. This file tells TypeScript how to compile your code and includes settings like output directory, target version, and more.
Basic tsconfig.json settings:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"outDir": "dist",
"rootDir": "src",
"strict": true
},
"include": ["src"]
}
The "outDir": "dist"
setting tells TypeScript to place the compiled JavaScript files in the dist
directory. The "rootDir": "src"
setting indicates that TypeScript should look for .ts
files inside the src
directory. You can also use tsc --init
to create tsconfig.json
file.
cd My-typescript-project
tsc --init
This creates the tsconfig.json file inside My-typescript-project with the required settings, you can manually create the file tsconfig.json and add the basic tsconfig settings provided by me.
Update the start script:
In your package.json
, update the start
script to include the build step before running the compiled JavaScript files:
{
"scripts": {
"start": "tsc && node dist/index.js"
}
}
If you have a single entry point file index.ts inside src then by the above setting you can use regular npm start
to compile all the files inside src folder to js and then run theindex.js
file. In this example, the start
script first runs the tsc
command to compile TypeScript files. Then, it uses the node
command to run the compiled JavaScript file located in the dist
directory (in this case,index.js
). With these changes, running npm start
will build your TypeScript code and then execute the compiled JavaScript code. Make sure your entry point file (e.g., index.ts
) is in the src
directory as specified in the tsconfig.json
.
Keep in mind that the exact configuration and settings may vary depending on your project’s structure and requirements, but these steps provide a basic setup for running TypeScript code in a Node.js environment.
Using ts-node for development environment:
install ts-node as a development dependency locally for your project.
cd My-typescript-project
npm install -D ts-node
this will install ts-node as a development dependency.
ts-node
is a TypeScript execution environment and REPL for Node.js, which allows you to directly run TypeScript files ( *.ts
) without explicitly compiling them to JavaScript. It’s particularly useful for development because it eliminates the need to manually compile your TypeScript code before running it.
If you choose to use ts-node
, you don’t have to worry about the build step and can directly run your TypeScript code like this:
ts-node src/index.ts
In this case, you won’t need a separate tsc
compilation step in your package.json
start
script. However, it’s worth noting that while ts-node
is convenient during development, it’s generally not recommended for production environments. For production, it’s better to pre-compile your TypeScript code to JavaScript using the TypeScript compiler (tsc
) and then run the compiled JavaScript code using node
. During development, ts-node
can be helpful for a faster development workflow, but for production deployments, it’s better to compile your TypeScript code using tsc
and then run the generated JavaScript files using node
. This will ensure better performance and compatibility with standard production environments.
Different types in typescript
Now that you have successfully set up the development environment for the typescript project, let’s understand the different types in typescript. I will give codes in JavaScript and corresponding code in TypeScript.
Basic Variable Declaration:
In JavaScript
let age = 25;
age = 'thirty'; // No error, JavaScript is dynamically typed
In TypeScript
let age: number = 25;
age = 'thirty'; // Error: Type '"thirty"' is not assignable to type 'number'
In TypeScript, we specify that the age
variable should have a type of number
, so assigning a string to it will result in a compilation error.
Function parameter and return type:
In JavaScript
function add(a, b) {
return a + b;
}
const result = add(5, '10'); // No error, JavaScript is dynamically typed
In TypeScript
function add(a: number, b: number): number {
return a + b;
}
const result: number = add(5, '10'); // Error: Argument of type 'string' is not assignable to parameter of type 'number'
In TypeScript, we explicitly specify that the add
function expects two parameters of type number
and will return a value of type number
. Attempting to pass a string as one of the arguments will trigger a compilation error.
Object with Specific Properties:
In JavaScript
const person = {
name: 'Sam',
age: 30,
};
person.address = '123 XYZ St'; // No error, JavaScript allows adding properties dynamically
In TypeScript
interface Person {
name: string;
age: number;
}
const person: Person = {
name: 'Sam',
age: 30,
};
person.address = '123 XYZ St'; // Error: Property 'address' does not exist on type 'Person'
In TypeScript, we can use interfaces to define the shape of an object. The Person
interface specifies that an object should have name
and age
properties. Trying to add the address
property to the person
object will cause a compilation error.
Array with Specific Element Type:
In JavaScript
const numbers = [1, 2, 3, 'four'];
In TypeScript
const numbers: number[] = [1, 2, 3, 'four']; // Error: Type 'string' is not assignable to type 'number'
In TypeScript, we can specify that the numbers
array should only contain elements of type number
. Mixing a string and a number in the array will result in a compilation error.
Type Inference:
let name = 'Alice';
name = 25; // No error, JavaScript is dynamically typed
let name = 'Alice';
name = 25; // Error: Type 'number' is not assignable to type 'string'
TypeScript employs type inference to deduce the type of a variable based on its initial value. In this case, TypeScript infers that the name
variable should have a type of string
because it is initialized with a string value. Therefore, assigning a number to it later will result in a compilation error.
Optional Properties in Objects:
const person = {
name: 'Bob',
age: 30,
};
interface Person {
name: string;
age?: number; // The '?' indicates the property is optional
}
const person: Person = {
name: 'Bob',
// age: 30, // age is optional, so it's okay to omit it
};
In TypeScript, you can define optional properties in interfaces by adding a ?
after the property name. This allows you to create objects that may or may not include the optional properties.
In TypeScript, you can define arrays and objects using explicit type annotations or inferred types.
Arrays Using Explicit Type Annotation:
// Array of numbers
let numbers: number[] = [1, 2, 3, 4, 5];
// Array of strings
let names: string[] = ['Alice', 'Bob', 'Charlie'];
// Array of mixed types
let mixedArray: (number | string)[] = [1, 'two', 3, 'four'];
Arrays Using Generic Array Type (Array<T>
):
// Array of numbers
let numbers: Array<number> = [1, 2, 3, 4, 5];
// Array of strings
let names: Array<string> = ['Alice', 'Bob', 'Charlie'];
// Array of mixed types
let mixedArray: Array<number | string> = [1, 'two', 3, 'four'];