Walter_Wally
Walter_Wally

Reputation: 15

How to define a concatenation function in typescript

In Typescript How can I define a interface Calculator that can support concatenation? Like:

interface Calculator {
    ...
}
 
let calcu: Calculator;
calcu(2).multiply(5).add(1)

I tried:

interface Calculator {
  (num: number): Calculator;
  multiply(num: number): Calculator;
  add(num: number): Calculator;
}

But I got the error that calcu is not instantiated:

Variable 'calcu' is used before being assigned

So my question is how I can define interface Calculator and how to instantiate calcu.

Upvotes: 0

Views: 30

Answers (1)

brunnerh
brunnerh

Reputation: 184526

Interfaces just define the shape of something, you probably should declare a class which can be instantiated with new.

e.g.

class Calculator
{
    constructor(public num: number) { }
    multiply(num: number)
    {
        this.num *= num;

        return this;
    }
    add(num: number)
    {
        this.num += num;

        return this;
    }
}

const calcu = new Calculator(2);
calcu.multiply(5).add(1);

console.log(calcu.num);

If you want to work directly with the interface and plain objects, that is possible but a huge pain, e.g.:

const calcu: Calculator = (() =>
{
    let value;

    const fun = function (num: number)
    {
        value = num;

        return fun;
    };
    fun['multiply'] = (num: number) =>
    {
        value *= num;
        return fun;
    };
    fun['add'] = (num: number) =>
    {
        value += num;
        return fun;
    };

    return fun;
})();

calcu(2).multiply(5).add(1);

(You probably also would want to define a function that returns the internal value, currently it is completely hidden.)

Upvotes: 3

Related Questions