xaviergonz / mobx-keystone

A MobX powered state management solution based on data trees with first class support for Typescript, support for snapshots, patches and much more
https://mobx-keystone.js.org
MIT License
554 stars 25 forks source link

Generic abstract class declaration #468

Closed hersentino closed 2 years ago

hersentino commented 2 years ago

I would like to create something like this:

abstract class A<T> {
  protected abstract method1: () => T;
}

class B extends A<string> {
  protected method1 = () => "helloword";
}

So I did :

a.ts :

import { Model, modelAction } from "mobx-keystone";

function createA<T>() {
  abstract class A extends Model({}) {
    @modelAction
    protected abstract method1: () => T;
  }

  return A;
}

export default createA;

b.ts :

import { ExtendedModel, model } from "mobx-keystone";
import createA from "./a";

@model("B")
class B extends ExtendedModel(createA<string>(), {}) {
  protected method1 = () => "helloword";
}

export default B;

but i'm getting those errors :

errors ![Screenshot 2022-07-07 at 16 05 27](https://user-images.githubusercontent.com/26276665/177804777-d4f73d37-f681-47af-8f8a-f7de70343a57.png) ![Screenshot 2022-07-07 at 16 05 19](https://user-images.githubusercontent.com/26276665/177804800-f0f2d102-bf42-4990-9ddc-f2250e34451e.png)

If I set declaration to false in my tsconfig.js, there are no more errors. But I need declaration to be true because my project is a lib so I need to generate and export .d.ts.

Can you help me to figure out what's wrong ?

Thanks :)

sisp commented 2 years ago

Have you looked at the "Factory Pattern / Generics" section in the docs? If you don't need runtime type-checking, you can have generic models without a factory.

hersentino commented 2 years ago

Oh it's exactly what i was looking for, thanks !