0

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.

1 Answer 1

3

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.)

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

Comments

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.