I am seeking advice on how to create an extension for a generic class in TypeScript specifically as a getter

Recently, I discovered how to create extensions in TypeScript:

interface Array<T> {
  lastIndex(): number
}

Array.prototype.lastIndex = function (): number { return this.length - 1 }

Now, I want to figure out how to make a getter from it. For example:

interface Array<T> {
  get lastIndex(): number
}

Array.prototype.lastIndex = function (): number { return this.length - 1 }

This way, I can easily call it as a getter in my code like someArray.lastIndex.

While searching for a solution, I came across an answer that seems promising but unfortunately the code doesn't compile for generic types. It's also quite cumbersome to write this way, but maybe I'm just asking too much from TypeScript: How to extend a TypeScript class with a get property?

Answer №1

When dealing with typescript interfaces, a getter is considered to be an implementation detail. You have the option to declare it as a normal readonly property and implement it as a getter.

interface Array<T> {
  readonly lastIndex: number
}

Object.defineProperty(Array.prototype, "lastIndex", {
  get: function () { return this.length - 1  }
});

By utilizing ES6 shorthand syntax,

Object.defineProperty(Array.prototype, "lastIndex", {
  get() { return this.length - 1  }
});

Answer №2

Consider the following approach:


interface Array<T> {
    finalIndex(): number;
    finalValue(): T
}

Array.prototype.finalIndex = function (): number { return this.length - 1 };
Array.prototype.finalValue = function (): any { return this[this.finalIndex()] };

let myArray = ['111,', '43242asd', 'asdasdas'];
console.log(myArray.finalValue());

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Basic exam but located in a place that is not valid

Here is a test I am working on: // import {by, element, browser} from "protractor"; describe('intro', () => { beforeEach(() => { browser.get(''); }); it('should have multiple pages', () => { let buttonOn ...

How can I bind the ID property of a child component from a parent component in Angular 2 using @Input?

I have a unique requirement in my parent component where I need to generate a child component with a distinct ID, and then pass this ID into the child component. The purpose of passing the unique ID is for the child component to use it within its template. ...

Mocking a third-party callback function in Jest for method implementation

Utilizing Nest + Cognito for user authentication in an application, I have a method within my Authentication service that requires testing/mocking: async cognitoRegister(userPool: CognitoUserPool, { name, password, email }: AuthRegisterInput): ...

Display an image on an HTML page based on the TypeScript data in an Ionic Angular application

After retrieving user profile data from the database and storing it in an observable, I am able to access properties such as profileData.username, profileData.msgnumber, and more. When profileData.avatar returns the name of the avatar the user is using, I ...

Utilize the optional chaining feature when accessing properties that may be optional

I recently encountered an issue in my Typescript project where accessing properties or functions of optional properties did not throw any errors. Here is an example: type Example = { bar?: string[] } const foo: Example = {} // Although no error occu ...

Create interfaces for a TypeScript library that is available on npm for export

I have a project in TypeScript that I am packaging as a library to be used by both JavaScript and TypeScript projects. After compiling, I upload the .js and .d.ts files to npm. The main.ts file exports the following: interface MyInterface{ // ... } clas ...

When utilizing an object as state in React, the `setState` function will only set

Currently, I am working on developing a React form that utilizes a custom Input component which I have created multiple times. The objective is to gather all the names and values from the form in the parent component: {inputName: value, inputName2: valu ...

Creating a factory function through typhography

I have a dynamically generated list of functions that take an argument and return different values: actions: [ param => ({name: param, value: 2}), param => ({label: param, quantity: 4}), ] Now I am looking to create a function that will gen ...

Enhance the functionality of 'takeWhile' by incorporating a limit parameter, similar to how 'take' operates

I am attempting to retrieve all pages until either there are no more pages or a certain limit (let's say 10 pages) is reached. If I follow this approach: obs.pipe(expand((page) => { return service.call(page).nextPage; }), take(10), takeWhil ...

Next.js TypeScript throws an error stating that the object 'window' is not defined

When trying to declare an audio context, I encountered an error stating that window is undefined. I attempted declaring declare const window :any above window.Context, but the issue persists. Does anyone have a solution for this problem? window.AudioCont ...

Error message in Typescript: When a class has initialized properties, a 'super' call must be the first statement in the constructor

I am currently facing some typescript errors in my project. Would you like to see a sample of the code that is causing the issue? Here is a snippet: module CoreWeb { export class Controller implements IController { public $q; ... This piece of cod ...

Ways to eliminate duplicate objects from an array using Angular 6

I'm having trouble removing duplicate value objects in an array and it's not working as expected. I believe the duplicate function is functioning correctly, but the changes are not being reflected in the li list. Can you pinpoint where I need to ...

Make sure to declare rest parameters first when using Typescript

I am dealing with a function that takes in multiple string arguments and one final argument of a complex type, which is called Expression. This particular code looks like this in JavaScript: function layerProp(...args) { const fields = args.slice(0, -1) ...

Generating a date without including the time

I recently started working with React (Typescript) and I am trying to display a date from the database without including the time. Here is my Interface: interface Games { g_Id: number; g_Title: string; g_Genre: string; g_Plattform: string; g_ReleaseDate: ...

What is the best way to implement type discrimination in TypeScript?

When using TypeScript with two interfaces combined as a union type, why doesn't it distinguish which type members can be declared? interface IFish { swim: () => void; } interface ICat { meow: () => void; } type Pet = IFish | ICat; const p ...

Issue with building Webpack React Router DOM configuration

I recently developed a React+Typescript app with Webpack 5 configuration completely from scratch. Everything was running smoothly in development mode, and I utilized React Router DOM version 6.23.1 for routing. However, once I built the app, some component ...

What is the best way to monitor parameter changes in a nested route?

I need assistance with managing routes const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'explore', component: ExploreComponent, children: [ { path: '', component: ProductListC ...

How do I verify if a boolean variable has been changed within an Angular service?

In my MatHorizontalStepper parent component, I utilize the subscribe function to monitor changes in an Observable within a service. The purpose is to automatically progress to the next step in the stepper when the observable switches from false to true. D ...

Dispatching an asynchronous function error in React with TypeScript and Redux - the parameter type is not assignable to AnyAction

Currently, I am in the process of developing a web application that utilizes Firebase as its database, along with Redux and TypeScript for state management. Within my code, I have a dispatch function nested inside a callback function like so: export const ...

Encountered an issue trying to access undefined properties while reading 'PP'

I am trying to showcase the data retrieved from my JSON file. Here is a glimpse of the information stored in the JSON => Within DTA > PP , I am specifically interested in displaying the variable NOMFAMILLE. An error message has caught my attentio ...