'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!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
