简体   繁体   中英

In Typescript, Is it possible to declare “type” from an existing object?

Say, I have a function like this:

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

Of course, it's type is (a: number, b: number) => number as function in Typescript.

If I want to use this function as an "argument" for another without really declare its type, I could use the default argument trick:

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

If I don't want it to be the default argument, do I have any other choice besides explicitly declare its type ?

In short, I don't want this function wrap(fn: (a: number, b: number) => number) { ... } , but I do want something like this function wrap(fn: like(plus)) { ... } .

What about using generics:

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);

Thanks to @OweR ReLoaDeD, type fn = typeof plus is a valid statement, so this works:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM