I want to determine the type of an optional argument. If the argument was specified, the return type should be the same as argument type. Otherwise, the return type must be undefined.
If I wrote fn<T>(p: T): T
, then the p
argument is not optional (I can't call the function like this fn()
). If I make it optional (fn<T>(p?: T): T
), then I will have to explicitly cast the return type to T
(as T
).
function fn<T>(p?: T): T {
return p // Without `as T`
}
const a = fn(1) // Must be `number` or `1`
const b = fn() // Must be `undefined` (without `fn(undefined)`)
See playground.
Is there any way to solve this?
CodePudding user response:
You can use Function overloads
Firstly, you define the two "type functions", the signatures that will indicate, what type of return type you get based on the parameters:
function fn(): undefined;
function fn<T>(p: T): T
Then, you will define the actual (runtime) implementation.
function fn<T>(p?: T): T | undefined {
return p
}