Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript declaring a generic function and assigning an arrow function to it

I'm trying to write a template function, that is an arrow function, and assign it to a const variable,

This is supposed to be of the form const method: MethodType<T> = <T>(...) => { ... }

But it complains when I try to type the variable method. Below is a snippet of the code:

export type KeyMethod<T> = (data: T) => any;

export interface DiffResult<T> {
    additions: T[];
    updates: T[];
    deletes: T[];
};

export type DiffMethod<T> = (oldState: T[], newState: T[]) => DiffResult<T>;

                     it complains about this template
                                   vvv
export const diffMethod: DiffMethod<T> = <T>(oldState: T[], newState: T[]) => {
    return {
        additions: [],
        updates: [],
        deletes: []
    }
};

Is there any way to do this? maybe I'm failing to follow the syntax, but I haven't found a similar example for that.

like image 792
Giora Guttsait Avatar asked May 10 '17 15:05

Giora Guttsait


1 Answers

As implied in a comment by Nitzan Tomer, you should write like the following.

export interface DiffResult<T> {
  additions: T[];
  updates: T[];
  deletes: T[];
}

export type DiffMethod = <T>(oldState: T[], newState: T[]) => DiffResult<T>;

export const diffMethod: DiffMethod = <T>(oldState: T[], newState: T[]) => {
  return {
    additions: [],
    updates: [],
    deletes: []
  };
};
like image 79
kimamula Avatar answered Nov 12 '22 15:11

kimamula