我们使用的模块不导出其所有参数的类型。这意味着参数经过类型检查,但我们无法在方法调用之前定义所需类型的变量。
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;
使用时Exported.bar
有没有办法让我首先定义参数以便正确输入?
let e = new Exported();
let x : /*???*/;
e.bar("any ideas?", x);
我想到了一种使用泛型来创建一个null
类型的Internal
所以我可以给x
正确的类型,但这非常笨重,有没有办法在type
定义并更干净地使用它?
function deduce<T>(f: (s: string, t: T) => any): T {
return null;
}
let x = deduce(e.bar);
使用条件类型进行类型推断是一个适合您的解决方案:
对于您的示例代码:
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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)