1 year ago

#320401

test-img

Richard

Why is a function with a required parameter assignable to a function type where the parameter is optional

Question

Simply put, I wonder why the following is valid:

type Func = (param?: string) => void;

const func: Func = (param: string) => {
  return;
};

The problem

In practice, this becomes a problem for callbacks, where the callback function may be invoked with one or no parameter, but the provided callback may just assume a parameter is provided, causing cannot read property of undefined errors.

Is there another type safe way to approach callbacks which may or may not be called with parameters?

Solution

strictNullChecks and strictFunctionTypes are required to invalidate the code example. Thanks for nudging me in the right direction Vlaz!

typescript

callback

optional-parameters

type-safety

0 Answers

Your Answer

Accepted video resources