Lay a solid foundation by understanding what TypeScript is, why it exists, and how it enhances JavaScript development.
Welcome to TypeScript! If you've been programming with JavaScript but ever felt like it's missing something, TypeScript is here to help. It adds a layer of static typing to JavaScript, giving you more control and catching errors early in your development process.
TypeScript is a superset of JavaScript that introduces static types. It compiles down to vanilla JavaScript and runs anywhere JavaScript can run.
// JavaScript
let age = 25;
age = 'twenty-five';
// TypeScript
let age: number = 25;
age = 'twenty-five'; // This line will throw an error
interface User {
id: number;
name: string;
age?: number;
}
const createUser = (data: Omit<User, 'id'>): User => ({
id: Date.now(),
...data
});
function multiply(x: number, y: number) {
return x * y;
}
multiply('5', '10'); // TypeScript will throw an error here
Welcome to Setting Up Your Environment! This section will guide you through creating a TypeScript development environment from scratch. Let's get started on your journey to mastering NestJS with TypeScript.
To work with TypeScript, you'll need to install Node.js and npm if they're not already installed on your system. Once Node.js is installed, you can use npm to install TypeScript globally.
# Install TypeScript globally
npm install -g typescript
Organize your project with the following directory structure:
/your-project
βββ src/
β βββ app/
β βββ domain/
β βββ infrastructure/
βββ test/
βββ .gitignore
βββ package.json
βββ tsconfig.json
The `tsconfig.json` file is essential for configuring your TypeScript project. Here's a basic configuration:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true
},
"include": [
"**/*.ts"
],
"exclude": [
"node_modules",
"**/*.test.ts"
]
}
// Run TypeScript compiler
npx tsc -w
// Build script example (package.json)
{
"scripts": {
"build": "tsc && cp src/tsconfig.json dist/tsconfig.json"
}
}
Welcome to your first adventure in TypeScript! Today, we'll guide you through creating, compiling, and running your very first TypeScript file. Get ready to take your JavaScript skills to the next level with type safety and better development practices.
// Save this as example.ts
const message: string = "Hello, TypeScript!";
console.log(message);
Here's what's happening in our first file: - We declare a variable message with an explicit type string. - We assign it the value "Hello, TypeScript!". - Finally, we log it to the console.
The tsconfig.json file is your project's configuration hub. It controls how TypeScript compiles your code. Here are some key options: - compilerOptions: Main settings like output directory, target version, and type checking behavior.
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src"
}
}
Question 1 of 14