2017-04-27 104 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'會起作用。順便謝謝你。 –

相關問題