Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

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)) { ... }.

like image 687
Phizaz Avatar asked Dec 08 '22 18:12

Phizaz


2 Answers

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) { }
like image 180
Phizaz Avatar answered Dec 11 '22 09:12

Phizaz


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);
like image 38
Remo H. Jansen Avatar answered Dec 11 '22 08:12

Remo H. Jansen