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 Loggeroverrides 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 |