Reputation: 1124
If have a TypeScript function f: A => B
. However I in my applications the input may be undefined, so I always have to write, say, const b?: B = a && f(a);
.
Can I change the function to include the check within the function (i.e., something like
(a: A | undefined) => B | undefined = (a => a && …)
but typed so that the return type does not contain undefined if a cannot be undefined, so that I can write either const b: B = f(a)
if a cannot be undefined, and const b?: B = f(a)
if a can be?
Upvotes: 0
Views: 801
Reputation: 35502
This is doable with function overloads:
// these are the two overloads
function f(x: number): string;
function f(x: number | undefined): string | undefined;
// this is the implementation, its type signature is not visible
function f(x: number | undefined): string | undefined {
return x?.toString();
}
Using the answers from this question, it can be extended to arrow functions:
const f: {
// these are the two overloads
(x: number): string;
(x: number | undefined): string | undefined;
} =
// this is the implementation, its type signature is not visible
// not sure why arrow functions make typescript dumber but "any" is now necessary as the return type
(x: number | undefined): any => x?.toString();
Upvotes: 2