# Install TypeScript as a dev dependency
npm install typescript --save-dev
# Compile a specific TypeScript file (e.g., app.ts)
npx tsc app.ts
Create a tsconfig.json
in your project root. This configuration enables strict type-checking and modern JavaScript features.
{
"compilerOptions": {
"target": "ES2020", // Use modern JS features
"module": "ESNext", // Use the latest module system
"moduleResolution": "node", // Node module resolution
"outDir": "./dist", // Compiled output directory
"rootDir": "./", // Root of your source files
"strict": true, // Enable all strict type-checking options
"esModuleInterop": true, // Allow default imports from non-ES modules
"skipLibCheck": true, // Skip type checking of declaration files
"forceConsistentCasingInFileNames": true, // Enforce consistent file naming
"resolveJsonModule": true, // Import JSON files as modules
"allowSyntheticDefaultImports": true, // Allow default imports even if module doesn't have one
"strictNullChecks": true, // Null and undefined are separate types
"noImplicitAny": true, // Disallow variables with an implied any type
"noUnusedLocals": true, // Error on unused locals
"noUnusedParameters": true, // Error on unused function parameters
"noFallthroughCasesInSwitch": true // Prevent fall-through in switch cases
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules", "dist"]
}
Primitive Types: boolean
, bigint
, null
, number
, string
, symbol
, undefined
Extended Types: any
, unknown
, never
, void
// Primitive Types
let num: number = 42;
let isDone: boolean = false;
let username: string = "Merrick";
// Array and Tuple
let numbers: number[] = [1, 2, 3];
let tuple: [number, string] = [1, "hello"];
// Object Type
let user: { name: string; age: number } = { name: "Merrick", age: 22 };
// Extended Type - Use sparingly
let anything: any = "This can be any type";
<aside> 💡
Avoid any
unless absolutely necessary; prefer unknown
when possible.
</aside>
Explicit return types make functions easier to read and maintain:
// Function Declaration with explicit return type
function add(a: number, b: number): number {
return a + b;
}
// Arrow Function with type inference
const multiply = (x: number, y: number): number => x * y;
// Usage examples
console.log(add(5, 3)); // 8
console.log(multiply(5, 3)); // 15
Using proper type annotations ensures you don’t misuse parameters:
function getUserName(callback: (data: string) => void): void {
// Imagine this function fetches a username asynchronously
const fakeUser = "Merrick";
callback(fakeUser);
}
getUserName((data) => {
console.log("Username:", data);
});
// The following callback would cause a compile error:
// getUserName((data) => {
// console.log(data * 2); // Error: Cannot multiply a string
// });