[英]In Typescript, Is it possible to declare “type” from an existing object?
說,我有一個這樣的功能:
function plus(a: number, b: number) { return a + b }
當然,它的類型是(a: number, b: number) => number
作為Typescript中的函數。
如果我想將此函數用作另一個函數的“參數”而不真正聲明其類型,則可以使用默認的參數技巧:
function wrap(fn = plus) { ... }
如果我不希望它成為默認參數, 除了顯式聲明其類型之外 , 我是否還有其他選擇?
簡而言之,我不需要此function wrap(fn: (a: number, b: number) => number) { ... }
,但我確實想要這樣的function wrap(fn: like(plus)) { ... }
。
那么使用泛型呢?
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);
感謝@OweR ReLoaDeD, type fn = typeof plus
是有效的語句,因此可以運行:
function plus(a: number, b: number) { return a + b }
function wrap(fn: typeof plus) { }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.