Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create type for un-exported typescript parameter

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); 
like image 341
Motti Avatar asked Oct 28 '22 20:10

Motti


1 Answers

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);
like image 99
千木郷 Avatar answered Nov 08 '22 12:11

千木郷