1

Suppose I have the following interface IFace, and an implementation of the interface Add:

interface IFace {
    add(a: number, b:number): number
}

class Add implements IFace {
   add(a,b)
}

When implementing the add() method in my Add class, is it possible to do so without specifying:

  1. the return type of the method?
  2. the types of arguments a and b?

I tried searching on Stack Overflow and the ​internet didn't find anything relevant.

1
  • I'd say yes, as functions (and methods) can be type-overloaded in typescript. Therefore it is not quite clear wether add(a, b) does implement IFace.add or not. Commented Apr 5, 2019 at 10:32

2 Answers 2

1

The type of each argument must be specified in the method signature of your Add classes add() function, as per the typescript syntax requirements. The return type of your Add classes add() function can however be inferred from the interface being implemented, and need not be provided explicitly.

The following would therefore be valid:

interface IFace {
    add(a: number, b:number): number
}

class Add implements IFace {

 /* Must supply number types for a and b, but return type of function be be omitted */
 add(a:number,b:number) {
    return a + b;
 }
}
Sign up to request clarification or add additional context in comments.

Comments

0

as from the official typescrip doc (https://www.typescriptlang.org/docs/handbook/interfaces.html) Interfaces describe the public side of the class, rather than both the public and private side. This prohibits you from using them to check that a class also has particular types for the private side of the class instance (so yes, you need to define the type of a & b, and d in this case)

interface ClockInterface {
    currentTime: Date;
    setTime(d: Date): void;
}

class Clock implements ClockInterface {
    currentTime: Date = new Date();
    setTime(d: Date) {
        this.currentTime = d;
    }
    constructor(h: number, m: number) { }
}

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.