TypeScript is an open-source programming language developed by Microsoft. It is a superset of JavaScript, meaning that any valid JavaScript code is also valid TypeScript code. TypeScript adds static types, classes, and interfaces to JavaScript, making it more suitable for large-scale applications and providing better tooling for developers.
Installation and Setup
To get started with TypeScript, you'll need to Install TypeScript globally using a package manager
pnpm install -g typescript
// or
pnpm install -D typescript@beta //for last updates in a specific project
You can use the
tsc
command followed by the file name to compile TypeScript files:tsc myfile.ts
Alternatively, you can create a
tsconfig.json
file to configure a development environment:tsc --init
Tsconfig.json setup:
- Set the
module
androotDir
for the project in the Modules configuration:
/* Modules */
"module": "commonjs" /* Specify what module code is generated. */,
"rootDir": "./src" /* Specify the root folder within your source files. */,
- Set the
outDir
andremoveComments
in the Emit configuration:
/* Emit */
"outDir": "./dist" /* Specify an output folder for all emitted files. */,
"removeComments": true /* Disable emitting comments. */,
"noEmitOnError": true /* Disable emitting files if any type checking errors are reported. */,
- Make sure the
strict
mode is set to true in the Type Cheking configuration
/* Type Checking */
"strict": true /* Enable all strict type-checking options. */,
Node environment setup:
- Install TypeScript type declarations for
Node.js
.
pnpm install -D @types/node
- Install
ts-node
andnodemon
dev dependencies:
pnpm i ts-node nodemon -D
- Set the
scripts
to initialize TypeScript.
"scripts": {
"start": "tsc && node ./dist/index.js",
"ts-node": "ts-node index.ts",
"dev": "nodemon index.ts"
},
Debugger setup
- Make sure to set the
sourceMap
to true in the Emit configuration:
"sourceMap": true /* Create source map files for emitted JavaScript files. */,
- Execute the Typescript compiler:
tsc
- Create the
launch.json
file and set thepreLaunchTask
to build over theTsconfig.json
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"skipFiles": ["<node_internals>/**"],
"program": "${workspaceFolder}\\src\\index.ts",
"preLaunchTask": "tsc: build - tsconfig.json", // Set this line in the configuration
"outFiles": ["${workspaceFolder}/**/*.js"]
}
]
}
Basic Types
TypeScript has a few basic types to help you define your variables:
boolean
: Represents true or false
number
: Represents a numeric value
string
: Represents a sequence of characters
array
: Represents a collection of elements
tuple
: Represents an ordered list of elements with specific types
enum
: Represents a collection of named constants
any
: Represents any type (use with caution)
void
: Represents the absence of a type, commonly used for functions that don't return a value
null
andundefined
: Represent the absence of a value
let isActive: boolean = true;
let age: number = 30;
let name: string = "John Doe";
let list: number[] = [1, 2, 3];
let tuple: [string, number] = ["age", 30];
enum Color {Red, Green, Blue}
let favoriteColor: Color = Color.Green;
Interfaces
Interfaces are used to define the structure of an object. They help with code completion and type checking.
interface Person {
name: string;
age: number;
greet(): void;
}
let john: Person = {
name: "John Doe",
age: 30,
greet() {
console.log(`Hello, my name is ${this.name}`);
}
};
john.greet(); // Hello, my name is John Doe
Classes
TypeScript supports classes, inheritance, and access modifiers (
public
, private
, and protected
).class Animal {
protected name: string;
constructor(name: string) {
this.name = name;
}
speak(): void {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
constructor(name: string) {
super(name);
}
speak(): void {
console.log(`${this.name} barks.`);
}
}
const dog = new Dog("Rex");
dog.speak(); // Rex barks.
Functions
Functions in TypeScript can have typed parameters and return types.
function greet(name: string): string {
return `Hello, ${name}`;
}
console.log(greet("John")); // Hello, John
// Optional parameters
function sayHello(name?: string): string {
return name ? `Hello, ${name}` : "Hello";
}
console.log(sayHello()); // Hello
// Default parameters
function welcome(name: string = "Guest"): string {
return `Welcome, ${name}`;
}
console.log(welcome()); // Welcome, Guest
Generics
Generics allow you to create reusable components that work with different types.
function identity<T>(arg: T): T {
return arg;
}
let output1 = identity<string>("Hello");
let output2 = identity<number>(42);
// Generic interfaces
interface GenericIdentityFn<T> {
(arg: T): T;
}
let myIdentity: GenericIdentityFn<number> = identity;
Modules
TypeScript supports importing and exporting modules using the ES6 module syntax.
example.ts
export function exampleFunction(): string {
return "This is an example function.";
}
main.ts
import { exampleFunction } from "./example";
console.log(exampleFunction()); // This is an example function.
Compile and run the code:
tsc main.ts
node main.js