jsebrech / tiny-signals

The tiniest implementation of signals, ideal for vanilla JavaScript projects.
The Unlicense
73 stars 0 forks source link

Typescript support #1

Closed felixranesberger closed 16 hours ago

felixranesberger commented 1 day ago

Hi, I just read the blogpost of your signal implementation and like the simplicity of the library. Since I use Typescript, I ported the code to typescript and use it on my local project.

I was wondering if I should create a pull request and submit my "port"?

We would need to add a Typescript compilation step though 🙌

This is my current code:

class Signal<T> extends EventTarget {
  #value: T;

  constructor(value: T) {
    super();
    this.#value = value;
  }

  get value() {
    return this.#value;
  }

  set value(value: T) {
    if (this.#value === value) return;
    this.#value = value;
    this.dispatchEvent(new CustomEvent('change'));
  }

  effect(fn: () => void) {
    fn();
    this.addEventListener('change', fn);
    return () => this.removeEventListener('change', fn);
  }

  valueOf() {
    return this.#value;
  }

  toString() {
    return String(this.#value);
  }
}

class Computed<T> extends Signal<T> {
  constructor(fn: (deps: Signal<unknown>[]) => T, deps: Signal<unknown>[]) {
    // @ts-expect-error - works fine, I don't know how to type this correctly
    super(fn(...deps));

    deps.forEach(
      // @ts-expect-error - works fine, I don't know how to type this correctly
      dep => dep.addEventListener('change', () => this.value = fn(...deps)),
    );
  }
}

export const signal = <T>(data: T) => new Signal(data);
export const computed = <T>(fn: () => T, deps: Signal<unknown>[]) => new Computed(fn, deps);
jsebrech commented 1 day ago

Thanks for sending this in! I would suggest making your own repo for this and sending me the link so I can add it to the readme.

felixranesberger commented 1 day ago

Thanks for the quick response! I just created the repository

I also added an additional effect function as described in the docs.

I hope the shoutout is fine for you, if you would like me to add some additional text, feel free to send me some text :)

Once again, many thanks for your work!

jsebrech commented 16 hours ago

I've added a link to the readme. Thanks again for contributing.