-
Notifications
You must be signed in to change notification settings - Fork 2
JavaScript & TypeScript
Qianhe Chen edited this page Nov 9, 2024
·
1 revision
JavaScript (JS) and TypeScript (TS) are the foundational languages of our project. While JavaScript is the standard language for web development, TypeScript adds static typing to help us write more robust and maintainable code.
JavaScript is a dynamic programming language that powers the web. Our project uses modern JavaScript (ES6+ features) to take advantage of the latest language improvements.
- Arrow Functions
// Traditional function
function add(a, b) {
return a + b;
}
// Arrow function
const add = (a, b) => a + b;- Destructuring
const user = {
name: 'John',
age: 30
};
// Extract properties
const { name, age } = user;- Spread/Rest Operators
// Spread operator
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
// Rest parameter
const sum = (...numbers) => numbers.reduce((a, b) => a + b, 0);- Async/Await
// Fetching data
async function fetchUserData() {
try {
const response = await fetch('/api/user');
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching user:', error);
}
}TypeScript is a superset of JavaScript that adds optional static typing. It helps catch errors early in development and provides better tooling support.
-
Type Safety
- Catch errors during development
- Better IDE support
- Self-documenting code
-
Enhanced Maintainability
- Easier refactoring
- Clear interfaces between components
- Better team collaboration
- Type Annotations
// Basic types
let name: string = "John";
let age: number = 30;
let isActive: boolean = true;
// Array types
let numbers: number[] = [1, 2, 3];
let names: Array<string> = ["John", "Jane"];- Interfaces
// Define a contract for objects
interface User {
id: number;
name: string;
email: string;
age?: number; // Optional property
}
// Use the interface
const user: User = {
id: 1,
name: "John",
email: "john@example.com"
};- Type Aliases
// Create custom types
type Point = {
x: number;
y: number;
};
type ID = string | number;- Generics
// Reusable components
function firstElement<T>(arr: T[]): T | undefined {
return arr[0];
}
// Usage
const numbers = firstElement([1, 2, 3]); // Type: number
const strings = firstElement(["a", "b"]); // Type: string{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}-
Always Use TypeScript for New Files
- Create new files with
.tsor.tsxextension - Define proper types for all variables and functions
- Create new files with
-
Type Inference
- Let TypeScript infer types when obvious
- Explicitly define types for function parameters and returns
-
Null Checking
// Use optional chaining
const userName = user?.profile?.name;
// Use nullish coalescing
const displayName = userName ?? "Anonymous";- Async Code
// Always properly type async functions
async function fetchData(): Promise<User[]> {
const response = await fetch('/api/users');
return response.json();
}-
Type Assertions
- Avoid using
asunless absolutely necessary - Use type guards instead when possible
- Avoid using
-
any Type
- Minimize use of
any - Use
unknownfor truly unknown types
- Minimize use of
-
Type Safety
// Bad
const data: any = fetchData();
// Good
interface ApiResponse {
users: User[];
total: number;
}
const data: Promise<ApiResponse> = fetchData();