I have attempted to implement this particular solution to prevent the calling of a generic function with the second type being equal to any
.
The following code snippet works fine as long as the first generic parameter is explicitly specified:
declare function f<V = any, A extends ISmth = ISmth>(a: IfAny<A, never, A>): V;
If I need V
to be the first parameter and optional (as it's the return type and cannot be inferred - either needs to be explicitly specified or simply be any), how can I correct the code?
I tried changing the default value, but it breaks any calls with an explicit first type:
declare function g<V = any, A extends ISmth = any>(a: IfAny<A, never, A>): V;
interface ISmth { x: number; }
type IfAny<T, Y, N> = 0 extends (1 & T) ? Y : N;
declare function f<V = any, A extends ISmth = ISmth>(a: IfAny<A, never, A>): V;
declare function g<V = any, A extends ISmth = any>(a: IfAny<A, never, A>): V;
declare var x: ISmth, y: any;
f(x); // Fine
f(y); // Fine: Argument of type 'any' is not assignable to parameter of type 'never'.
f<string>(x); // Fine
f<string>(y); // BAD: Should be an error, but compiles
g(x); // Fine
g(y); // Fine: Argument of type 'any' is not assignable to parameter of type 'never'.
g<string>(x); // BAD: Should NOT be an error
g<string>(y); // Fine: Argument of type 'any' is not assignable to parameter of type 'never'.