2

for example, I have an interface:

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

I'd like to add a sum() method that would give me a sum of values on any instance of this interface. What is a Typescript's way of doing this?

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

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

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

1
  • I need to work with classes I don't control. There are multiple of them, and the only thing in common is that all implement the common interface. Commented Mar 29, 2016 at 21:22

3 Answers 3

2

Extend a TypeScript interface via the extends keyword:

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

interface Bar extends Foo {
  sum() : number;
}

Implement the interface the following way:

class Baz implements Bar {
  public value1: number;
  public value2: number;
  sum() : number { return this.value1 + this.value2; }
}
var bar : Bar = new Baz();

Note: the implements Bar part is optional. Instances of Baz would still be assignable to Bar slots, as they have the required properties. However adding implements Bar will enforce the compiler to check the Baz class implements the Bar interface, throwing a compile time error on Baz if it doesn't.

Sign up to request clarification or add additional context in comments.

Comments

0

One way to do it is the following:

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

class Foo {
  public static sum(foo: Foo) {
    return foo.value1 + foo.value2;
  }
}

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

But maybe there is a more elegant way...

1 Comment

P.S. In practice, resorted to creating a wrapper for the interface instance and calling the function on the wrapper.
-1

I think you can do something like:

interface Foo1 extends Foo {
  suma(): number
}

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

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


You add this:

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

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

But this part does not understand well:

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

you do not want to do this?

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

1 Comment

@SergeyAldoukhov sorry but this part does not understand well -> and the function should not involve manual assignment of foo properties to some other class. Perhaps because of my bad English, but this will help you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.