To determine the type of an optional argument, I need to ensure that if the argument is specified, the return type matches the argument type. If the argument is not specified, then the return type should be undefined.
For example, if I define a function as fn<T>(p: T): T
, the p
argument is not optional and cannot be called without passing a value (fn()
). However, by making it optional using fn<T>(p?: T): T
, I must explicitly cast the return type to T
(as T
).
function fn<T>(p?: T): T {
return p // Without `as T`
}
const a = fn(1) // Should be `number` or `1`
const b = fn() // Should be `undefined` (without calling `fn(undefined)`)
Explore this concept in the TypeScript playground.
Is there a better approach to tackle this issue?