1

According to doc https://www.typescriptlang.org/docs/handbook/interfaces.html#function-types

I want to restrict the parameters of a function. I have written my function like this....

interface FuncType {
    (one: number, two: number, three: number): number;
}

let myfunc: FuncType = function (num1: number, num2: number, num3: number) {
    return num1 + num2 + num3;
}

let result = myfunc(10,20,30);
console.log(result);

This works great. But the problem is, if I do this...

let myfunc: FuncType = function (num1: number, num2: number) { //num3 is missing
    return num1 + num2;
}

// let result = myfunc(10,20);  //this gives an error.
let result = myfunc(10,20,30); // I had to give three parameters
console.log(result);

This works too. It is not showing any error. I was expecting it should give an error because num3 is not used there in the function definition.

It is also confusing because I cannot call myfunc with two paramters.

Is it not possible to make the function definition strict according to the interface?

3
  • What's your usecase? Commented Nov 2, 2020 at 0:15
  • I don't want to put my actual code there. But my problem is just like this situation. I want to define an interface that will rule creating functions implementing the interface. So that number of paramters in the function function definition will be same as interface. Commented Nov 2, 2020 at 0:59
  • Probably the way I am thinking there is no work-around. Same discussion here and ended with "Working as Intended" label. github.com/microsoft/TypeScript/issues/17868 Commented Nov 2, 2020 at 1:01

1 Answer 1

1

That is because TypeScript actually allows arguments to be discarded. From their documentation:

You may be wondering why we allow ‘discarding’ parameters [...]. The reason for this assignment to be allowed is that ignoring extra function parameters is actually quite common in JavaScript.

In your example, function (num1: number, num2: number) is a subtype of function (one: number, two: number, three: number) and is therefore considered valid.

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

1 Comment

That makes sense. But is there a way to restict it? like in my example, i cannot write the function with two parameters as the interface has three?

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.