Looking for an answer from the community on Typescript, require either of two function signatures
In my code, I am handling a callback where I need to either pass an error or leave the first argument as undefined and pass data as the second argument.
To describe this, I have created an interface as shown below:
type Callback = {
(error: undefined, value: string): void;
(error: Error): void;
}
function doThings(c: Callback) {
// Valid scenario with no error and a useful value.
c(undefined, '1');
// Scenario where something went wrong, so we provide an error but no value.
c(new Error());
// TS playground accepts this which is not ideal:
c(undefined);
}
function cOverload(error: undefined, value: string): void;
function cOverload(error: Error): void;
function cOverload(error: undefined | Error, value?: string) { }
doThings(cOverload)
I am facing two issues in this code, both related to how I define the function signature(s).
c(undefined);
is not flagged as an error by TS, but I want it to be treated as one.- In the implementation of cOverload, the parameter
value
is considered astring
. However, I do not need to check its type, and TS allows me to use functions like{ value.charAt(0); }
, while I expect it to raise concerns about value potentially being undefined.