We're using a module that does't export the type of all its parameters. This means that the arguments are typechecked but we can't define a variable of the required type before the method call.
Example:
// library
interface Internal { foo(): number } // I want to have a name for this un-exported interface
class A {
bar(s: string, x: Internal): string {
return s + x.foo(); // whatever
}
}
export const Exported = A;
When using Exported.bar
is there a way for me to first define the argument so that it's correctly typed?
let e = new Exported();
let x : /*???*/;
e.bar("any ideas?", x);
I thought of a way to use generics to create a null
of type Internal
so I can give x
the correct type but this is very clunky, is there a way to capture this type in a type
definition and use it more cleanly?
function deduce<T>(f: (s: string, t: T) => any): T {
return null;
}
let x = deduce(e.bar);
Type Inference with conditional types is a solution for you:
In the case of your sample code:
let e = new Exported();
// Type Inference Practice:
type ARG<T> = T extends ((a: any, b: infer U) => void) ? U : T;
type B = ARG<typeof e["bar"]>;
let x : B; // <-- let x : /*???*/;
e.bar("any ideas?", x);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With