Search code examples
typescriptfunctiongenericsanonymous-function

Typescript - Anonymous generic function


I've read quite a few things on the topic and got myself confused, if it turns out the answer is out there, I'll delete this question.

Why would that not work:

type SanitizeFunction = <T extends object = {}>(obj: object) => T;

const sanitizeAnimal: SanitizeFunction<Animal> = (obj) => ({...obj} as Animal);

Says: Type 'SanitizeFunction' is not generic. when it clearly is. I'm sure the solution is trying to hit me in the face and I'm refusing it lol

Any help would be gratefully received.


Solution

  • You need the generic T in the type before the assignment.

    type Animal = {};
    type SanitizeFunction<T extends object> = (obj: object) => T;
    
    const sanitizeAnimal: SanitizeFunction<Animal> = (obj: Animal) => ((obj));
    
    sanitizeAnimal({})