为未导出的打字稿参数创建类型 [英] Create type for un-exported typescript parameter

查看:33
本文介绍了为未导出的打字稿参数创建类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

示例:

//  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;

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

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);

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

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:

就您的示例代码而言:

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);

这篇关于为未导出的打字稿参数创建类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆