In search of a function type that can accommodate (x: X) => void
regardless of the type X
, but without resorting to the risky any
type.
Your preference lies in utilizing the --strict
set of compiler features, or possibly the --strictFunctionTypes
compiler option.
To achieve this, you can employ (x: never) => void
, with the parameter belonging to the impossible never
type:
let a: (x: never) => void;
a = (x: number) => { console.log(x.toFixed(2)) }; // valid
a = (x: string) => { console.log(x.toUpperCase()) }; // valid
a = (x: SomeInterface) => { console.log(x.a.toFixed(2)) }; // valid
The reason behind this lies in the contravariant nature of function types in relation to their parameter types. It stipulates that
((x: X)=>void) extends ((y: Y)=>void)
only if
Y extends X
. Note the reverse position: it's
Y extends X
, not
X extends Y
. This indicates that a function's type shifts counter to its parameter type.
In a scenario where someone requests a function of type (y: Y)=>void
to handle a value y
of type
Y</code, offering a function <code>f
of type
(x: X)=>void
where
Y extends X
ensures seamless operation. However, providing a function
g
of type
(z: Z)=>void
where
Z extends Y
bears risks, as illustrated in the article referencing covariance and contravariance.
It is important to note that despite (x: never) => void
being the answer to your specific question, it poses limitations due to the lack of narrowing for function types. Handling arguments of type never
can lead to runtime errors, as there exists no actual value of type never
to pass to the function.
While options like the unknown
type offer certain flexibility, narrowing possiblities remain limited for function types due to TypeScript's erased static type system that doesn't retain argument types at runtime.
To mitigate the challenges of (x: never) => void
, a suggested approach involves creating a type predicate function for runtime error capture.
Ultimately, while (x: never) => void
may address your initial query, practical implications unveil the necessity for alternative solutions in scenarios involving function/argument pairs.