Typescript and Forest

Forest and Typescript

Because Forest is a database of dynamic values, it is not completely compatible with Typescript; there is no way to easily introspect the parameters of custom actions, for instance. However, the value of a Forest instance can be injected with the typedLeaf generic:

import type { leafI, typedLeaf } from "@wonderlandlabs/forest/lib/types";
import {Forest} from "@wonderlandlabs/forest";
import {useState, useEffect} from 'react';
 
type PointValue = {
  x: number,
  y: number,
  label: string
}
 
const initial: PointValue = {
  x: 0,
  y: 0,
  label: 'Home'
}
 
const pointValue = new Forest({
  $value: initial,
  actions: {
    moveX(leaf: typedLeaf<PointValue>, offset: number) {
      leaf.do.set_x(leaf.value.x + offset);
    }
  }
})
 
const [value, setValue] = useState<PointValue>(pointValue.value);
useEffect(() => {
  const sub = pointValue.subscribe(setValue);
 
  return () => sub.unsubscribe();
}, [pointValue]);
 
Last updated on April 8, 2023