Let’s dive into when to use : Logger
(type annotation) vs as Logger
(type assertion) — with clear examples and explanation.
🧠 When to Use Which?
✅ Use : Logger (Annotation) when: | ✅ Use as Logger (Assertion) when: |
---|---|
You’re fully defining the object/function up front | You’re building or modifying the object in steps |
You want stricter type checking | You need to override TypeScript inference temporarily |
✅ 1. Type Annotation Example
🔹 When you’re defining everything at once.
interface Logger {
(message: string): void;
level: string;
enable(): void;
}
const logger: Logger = function (message: string) {
console.log(`[${logger.level.toUpperCase()}] ${message}`);
};
logger.level = "info";
logger.enable = () => {
console.log("Logger enabled!");
};
- Here, the function is fully declared and cast with a type annotation.
- TypeScript enforces all properties/methods must be present up front.
- Good for clean, strict, up-front definitions.
✅ 2. Type Assertion Example
🔹 When you’re building the object step-by-step (e.g., partial setup first, add props later).
interface Logger {
(message: string): void;
level: string;
enable(): void;
}
function createLogger(): Logger {
// Create function first
const log = function (msg: string) {
console.log(msg);
} as Logger; // TypeScript: "Trust me, this is a Logger"
// Add properties later
log.level = "debug";
log.enable = () => {
console.log("Logger enabled");
};
return log;
}
const logger = createLogger();
logger("Hello!"); // debug: Hello!
logger.enable(); // Logger enabled
- You’re gradually building the object.
- TypeScript normally wouldn’t allow adding props to a function like this.
as Logger
overrides the default inference, letting you “build” the type over time.
⚖️ Summary: When to Choose Which?
Scenario | Best Practice |
---|---|
You know the full shape at once | Use : Logger (Annotation) |
You’re constructing the object in multiple steps | Use as Logger (Assertion) |
You want maximum type safety | Prefer : Logger |
You’re working around TypeScript’s limitations temporarily | Use as Logger cautiously |