0

I am trying to migrate my app to typescript. I have kind of a base class that is my base library object. My classes created dependent on the base class. Below is a glimpse of my problem.

Below code works but autocomplete doesn't work. Couldn't figure out what should be defined for the type of Model.

const map = new WeakMap();
function weakRef<T>(context: T): T {
  // @ts-ignore
  if (!map.has(context)) { map.set(context, {}); }
  // @ts-ignore
  return map.get(context);
}
function getModel(provider: Provider) {
  return class Model {
    getSomething(key: string) {
      return weakRef(provider).configuration(key);
    }
  };
}

class Provider {
  configuration: (key: string) => string;
  constructor() {
    weakRef(this).configuration = (key: string) => {
      return key;
    };
    weakRef(this).Model = getModel(this);
  }
  get Model(): any {
    return weakRef(this).Model;
  }
  set Model(model: any) {
    weakRef(this).Model = model;
  }
}

const provider = new Provider();
const obj = new (provider.Model)();
console.log(obj.getSomething('test')); // This works, but autocomplete doesn't

I don't want to pass provider to the constructor in base model. Any help is appreciated, thanks.

1 Answer 1

2

You can get the return type of a function type with ReturnType<T>.

In this case, ReturnType<typeof getModel> should do the trick.

You can also fix the //@ts-ignore lines by constraining T to be an object type.

const map = new WeakMap();
function weakRef<T extends object>(context: T): T {
  if (!map.has(context)) { map.set(context, {}); }
  return map.get(context);
}

That said, I think this architecture is unnecessarily complicated. Why not just use this instead of a value tied to this?

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks it works. To answer your question, main reason is to make memory optimized library. you can look weakmap or weakset for more information.
@trd3v3lop that would make sense if multiple instances were sharing the same data... but they aren't, at least in your example. It is useless overhead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.