Augmenting Built-in JavaScript Objects with TypeScript
In TypeScript, you often encounter situations where you need to extend existing JavaScript types or modules that you don't have control over. Module augmentation is a powerful feature that allows you to add new properties or methods to existing types without modifying their original source code. This is particularly useful when working with third-party libraries or built-in JavaScript objects.
Problem Description
Your task is to implement module augmentation for a built-in JavaScript object. Specifically, you will augment the global Array type to include a new utility method called last. This method should return the last element of the array. If the array is empty, it should return undefined.
Key Requirements:
- You must use TypeScript's module augmentation feature to extend the
Arrayinterface. - The augmented
lastmethod should be accessible on all array instances. - The
lastmethod should accept no arguments. - The
lastmethod should return the last element of the array. - If the array is empty, the
lastmethod should returnundefined.
Expected Behavior:
When last() is called on an array, it should behave as described above.
Edge Cases:
- Calling
last()on an empty array. - Calling
last()on an array with a single element.
Examples
Example 1:
const numbers = [1, 2, 3, 4, 5];
const lastNumber = numbers.last();
console.log(lastNumber); // Expected output: 5
Explanation: The last() method is called on numbers, and it correctly returns the last element, 5.
Example 2:
const emptyArray: number[] = [];
const lastOfEmpty = emptyArray.last();
console.log(lastOfEmpty); // Expected output: undefined
Explanation: The last() method is called on an empty array. As per the requirements, it returns undefined.
Example 3:
const singleElementArray = ["hello"];
const lastOfString = singleElementArray.last();
console.log(lastOfString); // Expected output: "hello"
Explanation: The last() method is called on an array with a single element, and it returns that element.
Constraints
- The solution must be written in TypeScript.
- You are not allowed to modify the original JavaScript
Arrayprototype directly outside of a TypeScript declaration file context. - The solution should be performant and have minimal overhead.
Notes
To achieve module augmentation for a global type like Array, you'll need to declare a module that "matches" the global scope. A common way to do this is by creating a declaration file (e.g., index.d.ts) and placing your augmentation within a global declaration block.
Consider how TypeScript infers types. When you extend Array, ensure the return type of your last method correctly reflects the possibility of returning undefined.