Getting Started with TypeScript: A Beginner's Guide to Setting Up a Project with ts-node-dev
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:
1npm init -y
2tsc --init
The 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:
1npm 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:
1{
2 "compilerOptions": {
3 "rootDir": "./src",
4 "outDir": "./dist",
5 // other options
6 }
7}
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:
1"scripts": {
2 "start": "ts-node-dev --respawn --transpile-only ./src/index.ts"
3}
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:
1const greetFriends = (...rest: string[]): void => {
2 console.log(rest);
3};
4
5greetFriends("Alice", "Bob", "Charlie");
To compile your TypeScript code to JavaScript, run:
1tsc
This 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:
1npm start
Your 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.
1const greetFriends = (...rest: string[]): void => {
2 console.log(rest);
3};
Generics
Generics allow you to create reusable components with flexible types.
Using Generics in Types:
1type GenericArray<T> = Array<T>;
2
3const rollNumbers: GenericArray<number> = [22, 83, 12];
Using Generics in Interfaces:
1interface IPeople<T> {
2 name: string;
3 age: T;
4}
Generic Functions and Constraints
You can create generic functions to handle different types and use constraints to enforce certain type properties.
1const createArray = <T>(param: T): T[] => {
2 return [param];
3};
4
5const result1 = createArray<string>('Bangladesh');
Using Constraints:
1const addDetails = <T extends { name: string; age: number }>(myInfo: T) => {
2 const payment = false;
3 const newData = { ...myInfo, payment };
4 return newData;
5};
Utility Types
TypeScript provides several utility types to simplify common type transformations.
Pick and Omit:
1interface Person {
2 name: string;
3 email?: string;
4 contactNo: string;
5}
6
7type ContactInfo = Pick<Person, 'contactNo' | 'email'>;
8type NameOnly = Omit<Person, 'email' | 'contactNo'>;
Partial and Required:
1type OptionalPerson = Partial<Person>;
2type RequiredPerson = Required<Person>;
Readonly and Record:
1const person: Readonly<Person> = {
2 name: 'Hamim',
3 email: 'hamim@mail.com',
4 contactNo: '1234'
5};
6
7type 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!