簡體   English   中英

在Typescript中,是否可以從現有對象中聲明“類型”?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM