code2 - کد۲
352 subscribers
144 photos
63 videos
1 file
141 links
کد۲
💻 برنامه‌نویسی، فناوری و استارتاپ
Download Telegram
👨‍💻When to Use Which?

#javascript

🏹 Arrow Functions:
Short, simple functions or callbacks (e.g., event listeners, array methods like map, filter, reduce).
When you need to preserve "this" from the enclosing scope.

👍 Normal Functions:
When defining methods in objects or classes.
When you need dynamic "this" or access to the "arguments" object.
For constructors or functions requiring the "new" keyword.

@code2_ir
Interfaces or Types?

#javascript

Here are the key differences between TypeScript interfaces and types:

1. Syntax:
// Interface
interface User {
name: string;
age: number;
}

// Type
type User = {
name: string;
age: number;
}


2. Extension/Inheritance:
// Interface extends interface
interface Animal {
name: string;
}
interface Dog extends Animal {
bark(): void;
}

// Type extends type (using intersection)
type Animal = {
name: string;
}
type Dog = Animal & {
bark(): void;
}


3. Declaration Merging (Interface-only feature):
// Interfaces can be defined multiple times and will merge
interface User {
name: string;
}
interface User {
age: number;
}
// Result: User has both name and age

// Types cannot be reopened
type User = { name: string }
// Error: Cannot redeclare type User
type User = { age: number }


4. Union Types (Type-only feature):
// Only possible with type
type Status = "pending" | "approved" | "rejected";

// Can't do this with interface
type StringOrNumber = string | number;


5. Computed Properties:
// Works with type
type Keys = "firstname" | "lastname";
type DudeType = {
[key in Keys]: string;
}

// Doesn't work with interface
interface DudeInterface {
[key in Keys]: string; // Error
}


General recommendations:
- Use interface when:
- Defining object shapes/APIs
- You need declaration merging
- You're creating object-oriented designs
- You want clearer error messages

- Use type when:
- Creating unions or intersections
- Working with primitives
- Using mapped types
- Need complex type operations

Most modern TypeScript codebases tend to favor type because it's more flexible, but both are valid choices. The TypeScript team originally recommended interfaces, but types have become equally well-supported.