A
A
alex4answ2020-11-07 11:16:20
typescript
alex4answ, 2020-11-07 11:16:20

How to work with higher order functions?

Good afternoon, there is a higher order function that adds methods and properties to classes.

typescript

class Model {
  
  prototype: any;

  static find(id: number): number {
    return id;
  }

  save(): boolean {
    return true;
  }
}

function foo<M extends Model>(model: M) { // Какой тип она должна вернуть ?
  model.prototype.create = function (): void {
    // do something
  };

  model.findAll = function (): number[] { // Error Property 'findAll' does not exist on type 'M'.
    return [1, 2, 3];
  }

  return model;
}


Faced 2 problems that I just can not google and understand.

1. What type should this function return?
Tried to create a class with added methods, properties and return its type:
class NewModel {
  create(): void;
  static findAll(): number[];
}

function foo<M extends Model>(model: M): NewModel { ... }

But the compiler expects an object of the NewModel class from foo(), and not the extended class itself (I think something with typeof NewModel is needed here, but it didn’t work out yet, I just got confused)

2. How to extend classes if they don’t have added methods / properties ?:
Error Property 'findAll' does not exist on type 'M'.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Aetae, 2020-11-07
@alex4answ

Expand obviously with the keyword extends.
Everything else is just hacks and crutches. Typescript assumes that a class should not change on the fly in any way.

A
Alex, 2020-11-07
@Kozack

Your function should return Intersection Types
Something like this:
https://www.typescriptlang.org/play?#code/MYGwhgzh...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question