为未导出的打字稿参数创建类型

Mot*_*tti 5 types typescript

我们使用的模块不会导出其所有参数的类型。这意味着参数经过类型检查,但我们不能在方法调用之前定义所需类型的变量。

例子:

//  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;
Run Code Online (Sandbox Code Playgroud)

使用时Exported.bar有没有办法让我首先定义参数以便正确输入?

let e = new Exported();
let x : /*???*/;
e.bar("any ideas?", x);
Run Code Online (Sandbox Code Playgroud)

我想到了一种使用泛型来创建null类型的方法,Internal这样我就可以给出x正确的类型,但这很笨拙,有没有办法在type定义中捕获这种类型并更干净地使用它?

function deduce<T>(f: (s: string, t: T) => any): T {
    return null;
}
let x = deduce(e.bar); 
Run Code Online (Sandbox Code Playgroud)

千木郷*_*千木郷 2

使用条件类型进行类型推断是适合您的解决方案:

对于您的示例代码:

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);
Run Code Online (Sandbox Code Playgroud)