Consider the following TypeScript code that augments a third-party library's interface. What will be logged to the console?
import 'lodash'; declare module 'lodash' { interface LoDashStatic { customMethod(): string; } } import _ from 'lodash'; _.customMethod = () => 'Augmented!'; console.log(_.customMethod());
Think about how module augmentation adds new members to existing interfaces.
The code uses module augmentation to add customMethod to the LoDashStatic interface. Then it assigns a function to _.customMethod. This works both at compile time and runtime, so the output is the string returned by the function.
Choose the correct statement about augmenting third-party libraries in TypeScript.
Think about how TypeScript allows extending types without touching original files.
Module augmentation lets you add new properties or methods to existing interfaces or modules without modifying the original source code. It works by merging declarations at compile time.
Given this code snippet, why does TypeScript report an error?
import 'express'; declare module 'express' { interface Request { userId: number; } } import express from 'express'; const app = express(); app.use((req, res, next) => { console.log(req.userId); next(); });
Check if the module is imported before augmentation.
To augment a module, TypeScript requires the module to be imported before the declare module block. Without importing, the augmentation is not linked to the actual module, causing errors.
Choose the correct syntax to add a new function logInfo to the console namespace.
Think about how to augment global namespaces in TypeScript.
To augment a global namespace like console, you wrap the namespace declaration inside declare global. This merges the new function into the existing global namespace.
Given the following augmentation and usage, what is the type of result?
import 'moment'; declare module 'moment' { interface Moment { isWeekend(): boolean; } } import moment from 'moment'; const now = moment(); const result = now.isWeekend();
Consider the return type of the added method in the interface.
The augmentation adds isWeekend() returning a boolean to the Moment interface. Calling now.isWeekend() returns a boolean, so result is of type boolean.