An issue arises in StateFunction due to its optional second generic type that defaults to a value. Even when omitting this second generic, undefined
still needs to be passed as an argument, which contradicts the idea of it being optional.
While making args
truly optional by using args?
helps, it creates the need to check for null values even though the type is not nullable.
The option of overloading the function exists, but given the length of the actual function, this solution may not be optimal.
Is there a proper way to eliminate the need for passing the argument when the second generic type is left unspecified?
interface StateFunctionAction<T, P> {
(saved: T, args: P): void
}
const StateFunction = <T, P = undefined>(value : T, action: StateFunctionAction<T, P>) => {
let saved = value;
return (args : P) => action(saved, args);
}
const example1 = StateFunction<string>("Hello World", (saved) => console.log(saved))
example1(); // Help -> An argument for 'args' was not provided.
const example2 = StateFunction<string, number>("Hello World", (saved, n) => console.log(saved + " " + n))
example2(5);