1

I have some code like this

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

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

I hope typescript will give me an error like the method "setTime" should have two param, but it does not happen. Why?

5
  • It's probably perfectly valid to define another method with the same name with a different number of parameters. How is it supposed to know you intended to implement the interface and not just define another method? Commented Jun 23, 2017 at 16:53
  • Sorry, I cannot understand... if the interface cannot limit the parameters of the method, why we still write this code in the interface. Commented Jun 23, 2017 at 16:59
  • The interface is for when the code is used, not written. This isn't a Typescript specific "problem". This is why Java has a @override annotation, so the compiler can ensure that you're actually implementing the method properly. Commented Jun 23, 2017 at 17:02
  • Thanks. But I really want to restrict this method use two parameters with correct type, how can I do this.... Commented Jun 23, 2017 at 17:08
  • It is a very common Javascript pattern to ignore possible function parameters, such as if Clock's setTime ultimately didn't care about d2 so it just ignores that possible parameter. The Typescript team felt that this was a common enough pattern for Javascript developers that they made it so that you can always specify a smaller function header than what's required and it will type check. Source: github.com/Microsoft/TypeScript/wiki/… Commented Jun 23, 2017 at 17:21

1 Answer 1

2

If you declare them inline you will see an error like this. the interface provides a basis and if you override the type it thinks you are not declaring that variable(function) since the types do not match

setTime:(a:Date,b:Date)=>Date;
setTime = (a: Date)=> { 
  return a;
}

Subsequent variable declarations must have the same type. Variable 'setTime' must be of type '(a: Date, b: Date) => Date', but here has type '(a: Date) => Date'.

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.