If you're new to TypeScript and looking for a smooth development workflow, you've come to the right place. In this guide, we'll walk you through setting up a TypeScript project with ts-node-dev, a tool that allows you to run TypeScript code directly without pre-compiling it. We'll also explore some basic TypeScript concepts to get you started.
Step 1: Initialize Your Project
First, create a new project by running the following commands in your terminal:
npm init -y
tsc --initThe first command initializes a new Node.js project, while the second one sets up a TypeScript configuration file (tsconfig.json).
Step 2: Install ts-node-dev
Next, install ts-node-dev as a development dependency:
npm install ts-node-dev --save-dev'ts-node-dev' is a development tool that provides fast incremental compilation and automatic server restarting when code changes.
Step 3: Configure tsconfig.json
Open tsconfig.json and set the rootDir and outDir options to specify the directories for your TypeScript source files and the compiled JavaScript files:
{
"compilerOptions": {
"rootDir": "./src",
"outDir": "./dist",
// other options
}
}Make sure to create the src and dist directories if they don't already exist.
Step 4: Update package.json Scripts
In your package.json file, update the scripts section to include a start script for development:
"scripts": {
"start": "ts-node-dev --respawn --transpile-only ./src/index.ts"
}The --respawn flag automatically restarts the server when code changes, and the --transpile-only flag skips type checking for faster compilation times.
Step 5: Compile and Run Your Code
Write your TypeScript code in the src directory. For example, create a file named src/index.ts with the following content:
const greetFriends = (...rest: string[]): void => {
console.log(rest);
};
greetFriends("Alice", "Bob", "Charlie");To compile your TypeScript code to JavaScript, run:
tscThis will generate the compiled files in the dist directory. You can now delete any TypeScript files in the root directory if they were created by mistake.
Step 6: Start the Development Server
Run the following command to start the development server:
npm startYour TypeScript code will run with ts-node-dev, allowing for a smooth development experience.
Key TypeScript Concepts
Rest and Spread Operators
The rest operator (...) collects all arguments passed to a function into an array, while the spread operator expands an array into individual elements.
const greetFriends = (...rest: string[]): void => {
console.log(rest);
};Generics
Generics allow you to create reusable components with flexible types.
Using Generics in Types:
type GenericArray<T> = Array<T>;
const rollNumbers: GenericArray<number> = [22, 83, 12];Using Generics in Interfaces:
interface IPeople<T> {
name: string;
age: T;
}Generic Functions and Constraints
You can create generic functions to handle different types and use constraints to enforce certain type properties.
const createArray = <T>(param: T): T[] => {
return [param];
};
const result1 = createArray<string>('Bangladesh');Using Constraints:
const addDetails = <T extends { name: string; age: number }>(myInfo: T) => {
const payment = false;
const newData = { ...myInfo, payment };
return newData;
};Utility Types
TypeScript provides several utility types to simplify common type transformations.
Pick and Omit:
interface Person {
name: string;
email?: string;
contactNo: string;
}
type ContactInfo = Pick<Person, 'contactNo' | 'email'>;
type NameOnly = Omit<Person, 'email' | 'contactNo'>;Partial and Required:
type OptionalPerson = Partial<Person>;
type RequiredPerson = Required<Person>;Readonly and Record:
const person: Readonly<Person> = {
name: 'Hamim',
email: 'hamim@mail.com',
contactNo: '1234'
};
type MyObj = Record<'a' | 'b' | 'c', string>;Conclusion
Setting up a TypeScript project with ts-node-dev can greatly improve your development workflow by providing fast and efficient compilation and automatic server restarts. By following this guide, you now have a basic TypeScript project ready to go, along with an understanding of key TypeScript features. Happy coding!
