2017-04-27 102 views
1

说,我有这样的功能:在Typescript中,是否可以从现有对象声明“type”?

function plus(a: number, b: number) { return a + b } 

当然,它的类型是(a: number, b: number) => number为打字稿功能。

如果我想使用此功能为“参数”另一个没有真正宣布它的类型,我可以使用默认参数招:

function wrap(fn = plus) { ... } 

如果我不希望它成为默认参数,除了明确声明其类型外,还有其他选择吗?

总之,我不想这function wrap(fn: (a: number, b: number) => number) { ... },但我确实想要这样的东西function wrap(fn: like(plus)) { ... }

回答

2

感谢@OweR重装上阵,type fn = typeof plus是一个有效的声明,所以此工程:

function plus(a: number, b: number) { return a + b } 
function wrap(fn: typeof plus) { } 
3

怎么样使用泛型:

function plus(a: number, b: number) { return a + b } 

function wrap<T extends Function>(fn: T) { 
    fn(); 
} 

// Works 
var wrappedPlus = wrap<typeof plus>(plus); 

// Error: Argument of type '5' is not assignable to parameter of type '(a: number, b: number) => number'. 
var wrappedPlus = wrap<typeof plus>(5); 

// Error: Argument of type '5' is not assignable to parameter of type 'Function'. 
var wrappedPlus = wrap(5); 

function concat(a: string, b: string) { return a + b } 

// Error: Argument of type '(a: number, b: number) => number' is not assignable to parameter of type '(a: string, b: string) => string'. 
var wrappedPlus = wrap<typeof concat>(plus); 
+0

刚刚意识到'型FN = typeof运算plus'是有效的声明。我简化了这个问题,实际上我想用一个更高阶的函数,在这种情况下,我不认为'typeof'会起作用。顺便谢谢你。 –

相关问题