sudip
sudip

Reputation: 2850

How to enforce mandatory argument in Typescript Function Type?

I am new to Typescript and have a doubt regarding function type.

I have the following type :

type IMyTest<R> = (
    arg1: number,
    arg2: string,
    arg3: number
) => R;

Now, following signature is valid (doesn't give me an error) and I don't understand why its valid. As per my understandings, arg2 and arg3 are not marked as optional using the "?" sign and so the TypeScript compiler should raise an error, but it's not:

const myTest3: IMyTest<string> = (arg1: number):string => {

    return "any string";
};

Live example on the playground

Is there any way to make the arguments mandatory ?

Right now, arg1?:string is same as arg1:string. According to my understandings,without the "?" sign, an argument is mandatory. But, that's not the case in here.

Upvotes: 3

Views: 1384

Answers (1)

Aleksey L.
Aleksey L.

Reputation: 37918

Have a look at type compatibility rules

let x = (a: number) => 0;
let y = (b: number, s: string) => 0;

y = x; // OK
x = y; // Error

"Discarding" parameters (like in your example) is allowed because the implementation doesn't care if these parameters provided or not (you won't get any error at runtime).

This pattern is actually quite common in JavaScript. For example, Array#forEach provides three parameters to the callback function: the array element, its index, and the containing array. Nevertheless, it’s very useful to provide a callback that only uses the first parameter.

const items = [1, 2, 3];

// Don't force these extra parameters
items.forEach((item, index, array) => console.log(item));

// Should be OK!
items.forEach(item => console.log(item));

Upvotes: 2

Related Questions