TS Get Started
This section will guide you through the initial setup steps for TypeScript, including installation, compiler configuration, and running your first TypeScript file.
Key Topics
Installing TypeScript
You can install TypeScript globally or as a local development dependency. A global install allows you to use the tsc
command directly from your terminal.
# Global installation
npm install -g typescript
# Local installation within a project
npm install --save-dev typescript
Explanation: For most project setups, installing TypeScript locally in your project is sufficient. A global installation can be helpful for quick tests or demos.
tsconfig.json
The tsconfig.json
file lets you configure how the TypeScript compiler behaves. Create this file in the root of your project to manage compilation settings such as target JavaScript version, module resolution, and more.
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"strict": true,
"outDir": "./dist"
},
"include": ["src/**/*"]
}
Explanation: In this example, TypeScript compiles to ES6 syntax, uses CommonJS modules, enforces strict type-checking, and outputs compiled files to a dist
folder. It includes all TypeScript files in the src
folder.
Your First TypeScript File
Let’s create a basic TypeScript file and compile it. Assume you have a folder structure where src/index.ts
is your main file.
// src/index.ts
function welcome(name: string): string {
return `Welcome, ${name}!`;
}
console.log(welcome("TypeScript User"));
Output
Welcome, TypeScript User!
Explanation: Run tsc
to compile the code, and then node dist/index.js
(assuming outDir
is dist
) to see the output.
Key Takeaways
- Installation: You can install TypeScript globally or locally depending on your workflow.
- tsconfig.json: Central configuration file to manage how the compiler processes your code.
- Compile & Run: Use
tsc
to transpile to JavaScript, and then run in any JS environment.