Ways to expand a Typescript interface

As an illustration, imagine I have the following interface:

interface Bar {
  value1: number;
  value2: number;
}

I want to include a method called calculateSum() that will return the sum of values on any object implementing this interface. How can this be achieved in Typescript?

I am looking to create a function like this:

function outputBarSum(bar: Bar) {
  console.log(???);
}

This function should not require manually assigning properties from bar to another class.

Answer №1

Expanding a TypeScript interface using the extends keyword:

interface A {
  num1: number;
  num2: number;
}

interface B extends A {
  total() : number;
}

To implement the interface, follow this example:

class C implements B {
  public num1: number;
  public num2: number;
  total() : number { return this.num1 + this.num2; }
}
var b : B = new C();

Note: The use of implements B is not required. Instances of C can still be assigned to B. However, including implements B will prompt the compiler to verify that the C class adheres to the B interface, resulting in a compile time error if it doesn't.

Answer №2

If you're looking for a solution, consider the code snippet below:

interface Bar {
  number1: number;
  number2: number;
}

class Bar {
  public static calculateSum(bar: Bar) {
    return bar.number1 + bar.number2;
  }
}

function displayBarSum(bar: Bar) {
  console.log(Bar.calculateSum(bar));
}

Of course, there may be other ways to tackle this problem with more elegance...

Answer №3

One possible solution could be:

interface Foo1 extends Foo {
  suma(): number
}

interface Foo{
  value1: number;
  value2: number;
}

http://www.typescriptlang.org/docs/handbook/interfaces.html#extending-interfaces


Here's an additional requirement:

I need to be able to write a function like this:

function printFooSum(foo: Foo) {
  console.log(???);
}

A point of confusion arises here:

and the function should not involve manual assignment of foo properties to some other class.

Are you trying to avoid this?

function printFooSum(foo: Foo) {
  console.log(foo.value1 + foo.value2);
}

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

Angular data binding between an input element and a span element

What is the best way to connect input texts with the innerHTML of a span in Angular6? Typescript file ... finance_fullname: string; ... Template file <input type="text" id="finance_fullname" [(ngModel)]="finance_fullname"> <span class="fullnam ...

Utilizing TypeScript's type inference within a higher order function to determine the input of the returned function

I have been working on creating a versatile "pipe" function that takes a series of map functions to transform an input and then output the result of the final map function. Initially, I only implemented a basic version that accepts one map function as a pa ...

Creating valuable properties in TypeScript is a skill that requires knowledge and practice

In TypeScript, there is a unique feature available for defining properties with values using the `value` keyword. class Test { constructor(private value: number = 123) { } public MyValueProperty: number = 5; } Here is how you can define such ...

Accessing properties using bracket notation in Typescript is a powerful feature that

I wish to retrieve a typed object using bracket notation like this: interface IFoo { bar: string[]; } var obj: IFoo = { bar: ["a", "b"] } var name = "bar"; obj[name]. // type information lost after dot As per the specification 4.10, it seems to be t ...

Troubleshooting Axios errors when using createAsyncThunk function

Can someone help me with handling errors in createAsyncThunk using TypeScript? I attempted to declare the returned type and params type with generics, but when it came to error handling typing, I found myself resorting to just using 'any'. Let& ...

The testString's dependencies are unresolved by Nest

Encountered Problem: Facing the following issue while running a unit test case Nest is unable to resolve the dependencies of the testString (?). Please ensure that the argument SECRET_MANAGER_SERVICE at index [0] is available in the context of SecretMa ...

Create a grade array for a group, with each grade containing a nested section array. Within each section, include

I currently have an array of objects where I need to organize each grade into separate arrays. Within each grade array, I want to include the corresponding sections and subjects. The data structure consists of grades, with each grade containing a section ...

Creating and sharing a project in Typescript

My typescript project tends to have its code scattered across multiple files during development. Is there a recommended method for packaging this project into a single js and d.ts file for distribution? ...

Verify in Typescript if there is at least one value supplied

Looking for a solution: function takeOneOfOrThrow(firstOptionalVariable : string | undefined, secondOptionalVariable : string | undefined) { let result : string; if (!firstOptionalVariable && !secondOptionalVariable) { throw new E ...

What is the best way to add an external .js file to my Angular 2 application?

I'm currently working on a project using Angular 2's TypeScript API along with webpack to develop a web application. However, I've encountered an issue where one of my components needs to utilize functions from an external .js file that is p ...

The disappearance of the "Event" Twitter Widget in the HTML inspector occurs when customized styles are applied

Currently, I am customizing the default Twitter widget that can be embedded on a website. While successfully injecting styles and making it work perfectly, I recently discovered that after injecting my styles, clicking on a Tweet no longer opens it in a ne ...

The error message "SyntaxError: Cannot use import statement outside a module" is encountered when trying to import node-fetch in a Typescript file

I'm facing some challenges with the development of a typescript library npm package. The problem arises when I attempt to import node-fetch for fetch calls. To illustrate my issue, I have set up a sample git repository. These are the commands I used ...

Automatic browser refresh with the `bun dev` command

Currently experimenting with the latest bun platform (v0.1.6) in conjunction with Hono. Here are the steps I followed: bun create hono test-api cd test-api bun dev After running the server, the following message appears: $ bun dev [1.00ms] bun!! v0.1.6 ...

Setting a default time on a p-calendar: A step-by-step guide

I am currently using the following p-calendar component in my webpage: <p-calendar [style]="{'width':'100%'}" [inputStyle]="{'width':'100%'}" dateFormat="dd-mm-yy" [fo ...

Is there a way to verify if a component contains a child node with the tag <template></template>?

Consider the scenario with MyComponent: <div [my-component]="'text'"></div> Within the code, I have access to this.viewContainerRef, which refers to the DOM node itself (<div>). However, for customization purposes, a user mig ...

The 'initializeOnMount' property is a necessary requirement within the definition of the 'MoralisProviderInitializedProps' type

I encountered an unexpected issue with the code below: Type '{ children: Element; appId: string | undefined; serverUrl: string | undefined; }' is not compatible with type 'IntrinsicAttributes & MoralisProviderProps'. The property ...

Can you explain the distinction between 'bigint' in lowercase and 'BigInt'?

Currently, I am in the process of updating some TypeScript code that utilizes an external library for handling big numbers to BigInt (ES2020). However, the linter is throwing numerous errors which I find quite perplexing. https://i.sstatic.net/VnQSK.png ...

Altering a public variable of a component from a sibling component

Within my application, I have two sibling components that are being set from the app.component: <my-a></my-a> <my-b></my-b> The visibility of <my-a> is determined by a public variable in its component: @Component({ module ...

I am looking to transfer information from Angular 4 to Java servlet (cross-domain)

Having trouble sending data from Angular 4 to a Java servlet due to access control restrictions. Need to figure out how to properly insert data into the database using the Java servlet. Here is my code snippet: import { Injectable } from '@angular/ ...

What is the issue with this asynchronous function?

async getListOfFiles(){ if(this.service.wd == '') { await getBasic((this.service.wd)); } else { await getBasic(('/'+this.service.wd)); } this.files = await JSON.parse(localStorage.getItem('FILENAMES')); var ...