Typescript
1. What is TypeScript?
- Superset of JavaScript: TypeScript includes all JavaScript features and adds static typing, interfaces, and advanced tooling support.
- Type Safety: Allows you to catch type-related errors at compile time rather than runtime.
- Compiles to JavaScript: TypeScript code is transpiled to JavaScript, ensuring compatibility with browsers and JavaScript environments.
- Used for Large-Scale Projects: Great for large, complex projects with multiple developers, as it provides better maintainability and readability.
2. Key Features
Static Typing: Adds types to variables, functions, and objects.
let message: string = "Hello, TypeScript!"; let count: number = 42;
Type Inference: Automatically infers types when they are not explicitly declared.
let inferred = "This is inferred as a string";
Interfaces: Defines the structure of objects, ensuring consistency.
interface User { : number; id: string; name }
Enums: Defines a set of named constants.
enum Direction { , North, South, East, West }
Union Types: A variable can have multiple types.
let value: string | number; = "Hello"; // Valid value = 42; // Valid value
Generics: Enables reusable, type-safe components.
function identity<T>(value: T): T { return value; }
Decorators (Experimental): Adds metadata to classes and members, often used in frameworks like Angular.
Component({...}) @class MyComponent {}
Modules: Supports
ES6
modules for importing and exporting code.import { myFunction } from './myModule'; export function myFunction() {}
Strict Null Checks: Ensures variables are not
null
orundefined
unless explicitly allowed.Advanced Tooling: Better IntelliSense, autocomplete, and refactoring support in IDEs like Visual Studio Code.
3. Installation
Install TypeScript globally via npm:
npm install -g typescript
Check the installed version:
tsc --version
4. Setting Up a TypeScript Project
a. Initialize a New Project
Create a new directory:
mkdir my-project && cd my-project
Initialize
package.json
:npm init -y
Install TypeScript locally:
npm install typescript --save-dev
Create a
tsconfig.json
:npx tsc --init
b. Example tsconfig.json
{
"compilerOptions": {
"target": "ES6",
"module": "ES6",
"strict": true,
"esModuleInterop": true,
"outDir": "./dist",
"rootDir": "./src",
"resolveJsonModule": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
5. Compiling TypeScript
Compile .ts
files to .js
:
npx tsc
You can also compile a single file:
npx tsc file.ts
Run the JavaScript file:
node dist/file.js
6. TypeScript vs JavaScript
Feature | TypeScript | JavaScript |
---|---|---|
Typing | Statically typed (type checking at compile time). | Dynamically typed. |
Error Detection | Compile-time errors for type mismatches. | Errors detected at runtime. |
Tooling | Superior tooling and editor support. | Limited tooling capabilities. |
Backward Compatibility | Compiles to ES3+ JavaScript for compatibility. | Runs directly in browsers or Node.js. |
7. Advanced Features
a. Type Aliases
Alias complex types for readability:
type Point = { x: number; y: number };
let pt: Point = { x: 10, y: 20 };
b. Intersection Types
Combine multiple types:
type Admin = { id: number; role: string };
type User = { name: string };
type AdminUser = Admin & User;
c. Utility Types
TypeScript includes built-in utility types like Pick
, Partial
, and Omit
:
interface User {
: number;
id: string;
name: string;
email
}type PartialUser = Partial<User>; // All properties are optional
type PickedUser = Pick<User, "id" | "email">;
d. Type Guards
Refine types at runtime:
function isString(value: unknown): value is string {
return typeof value === 'string';
}
8. TypeScript with Frameworks
a. React
Install TypeScript for React:
npx create-react-app my-app --template typescript
Use .tsx
for TypeScript files with JSX.
b. Node.js
Install TypeScript for Node.js:
npm install @types/node --save-dev
c. Angular
Angular uses TypeScript by default.
9. Integrating TypeScript into Existing Projects
Add TypeScript to an existing project:
npm install typescript --save-dev
Rename
.js
files to.ts
and fix type errors.Gradually enable strict checks in
tsconfig.json
.
10. TypeScript with Third-Party Libraries
Install type definitions for popular libraries:
npm install @types/lodash --save-dev
11. Tooling and Ecosystem
- Editors: Works best with Visual Studio Code.
- Linting: Use ESLint with TypeScript.
- Testing: Use frameworks like Jest or Mocha with TypeScript.
12. Advantages of TypeScript
- Improved Code Quality: Early detection of bugs through static typing.
- Refactoring Support: Easier to refactor large codebases with type safety.
- Tooling: Enhanced IntelliSense, auto-completion, and debugging.
- Large Community: Widespread adoption and support.
13. Disadvantages of TypeScript
- Learning Curve: Requires learning types and new syntax.
- Extra Compilation Step: Must compile
.ts
to.js
. - Overhead: Adds some complexity for small projects.
14. TypeScript vs Other Languages
Feature | TypeScript | JavaScript | Python | Java |
---|---|---|---|---|
Typing | Static (optional) | Dynamic | Dynamic | Static |
Compilation | Yes | No | No | Yes |
Runtime Speed | Fast | Fast | Slower | Fast |
Popularity | Growing | High | High | Stable |