Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Object.defineProperty is not respected #41637

Closed
droganov opened this issue Nov 22, 2020 · 2 comments
Closed

Object.defineProperty is not respected #41637

droganov opened this issue Nov 22, 2020 · 2 comments
Labels
Question An issue which isn't directly actionable in code

Comments

@droganov
Copy link

droganov commented Nov 22, 2020

I've made a factory which works in JS, but it is not respected in TS

function model(defaultState) {
  const callbacks = {};

  function init() {
    let state = defaultState;
    return Object.entries(callbacks).reduce(
      (acc, [key, callback]) => ({
        ...acc,
        [key]: (...args) => {
          state = callback(state, ...args);
          return state;
        },
      }),
      {}
    );
  }

  Object.defineProperty(init, "on", {
    set(moreCallbacks) {
      Object.assign(callbacks, moreCallbacks);
    },
  });

  return init;
}

const m = model(0);

m.on = {
  increment: (state) => ++state,
  decrement: (state) => --state,
}



console.log(
  'increment: ', m().increment(),
  'decrement: ', m().decrement(),
);

So in TS when I call m.on I get Property 'on' does not exist on type 'ModelInstance<number, { reset(): number; }>'.ts(2339)

I expect that TS would accept m.on and then correctly apply types to the callbacks. I suspect this is a bug, but if it's not, then how I type this?

Below is my original function which works via generics, but I'm looking to unload the arguments as in the above example:

import { Dispatch } from "../dispatch";
import { Mediator } from "../mediator";

export type Model = typeof model;

type FactoryProps<S> = {
  dispatch: Dispatch;
  initialState?: S;
  getState(): S;
  mediator: Mediator;
  setState(nextState: S): void;
};

type Instance<S, A extends CallbacksMap<S>> = ActionProducers<S, A> & {
  state: S;
  subscribe(callback: () => void): () => void;
};

interface Factory<S, A extends CallbacksMap<S>> {
  (props: FactoryProps<S>): Instance<S, A>;
}

interface Callback<S> {
  (state: S, ...extraArgs: any[]): S;
}

type CallbacksMap<S> = Record<string, Callback<S>>;

type ActionProducers<S, A extends CallbacksMap<S>> = {
  [P in keyof A]: (
    ...args: Parameters<A[P]>[1] extends undefined
      ? []
      : [action: Parameters<A[P]>[1], ...extra: any[]]
  ) => void;
};

export const model = <S, A extends CallbacksMap<S>>({
  id,
  actions,
  defaultState,
  events,
}: {
  id: string;
  defaultState: S;
  actions?: A;
  events?: CallbacksMap<S>;
}) => {
  const factory: Factory<S, A> = ({
    dispatch,
    initialState,
    getState,
    mediator,
    setState,
  }) => {
    const getLocalType = (topic: string) => `${id}/${topic}`;
    const initType = getLocalType("@init");
    const updateType = getLocalType("@update");

    function runCallback(callback: Callback<S>, ...args: any[]) {
      const nextState = callback(getState(), ...args);
      setState(nextState);
      mediator.publish(updateType);
    }

    Object.entries(events || []).forEach(([key, callback]) => {
      key.split(",").forEach((topic) => {
        mediator.subscribe(
          topic.trim(),
          (...args: Parameters<typeof callback>) => {
            runCallback(callback, ...args);
          }
        );
      });
    });

    setState(typeof initialState === "undefined" ? defaultState : initialState);

    mediator.publish(initType, { type: initType });

    return {
      ...Object.entries(actions || {}).reduce((acc, [topic, callback]) => {
        const type = getLocalType(topic);
        mediator.subscribe(type, (...args: any[]) => {
          runCallback(callback, ...args);
        });
        return {
          ...acc,
          [topic]: (action, ...extraArgs) => {
            dispatch({ ...action, type }, ...extraArgs);
          },
        };
      }, {} as ActionProducers<S, A>),
      get state() {
        return getState();
      },
      subscribe(callback: () => void) {
        return mediator.subscribe(updateType, callback);
      },
    };
  };

  const extras = {
    id,
    defaultState,
  };

  return Object.assign(factory, extras);
};
@ExE-Boss
Copy link
Contributor

ExE-Boss commented Nov 24, 2020

That’s because Object.defineProperty is untyped with special handling for JS code.


Full support for Object.defineProperty in TypeScript depends on #34636 (#40562).

@andrewbranch andrewbranch added the Question An issue which isn't directly actionable in code label Nov 25, 2020
@typescript-bot
Copy link
Collaborator

This issue has been marked as 'Question' and has seen no recent activity. It has been automatically closed for house-keeping purposes. If you're still waiting on a response, questions are usually better suited to stackoverflow.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

4 participants