#Need help typing a function that returns a promise.

1 messages · Page 1 of 1 (latest)

thorn seal
#

I'm building a modal that is shared through the app with a Context, and the context returns a function that populate the modal and returns a promise.

The context declaration is:

const ConfirmerContext = createContext({
  show: (options: {
    title?: string;
    description?: string;
    cancelLabel?: string;
    confirmLabel?: string;
    colorScheme?: string;
  }) => Promise<boolean>,
});

And the functions is:

  function handleShow({
    title = 'Title',
    description = '',
    cancelLabel = 'Cancel',
    confirmLabel = 'Confirm',
    colorScheme = 'blue',
  }: {
    title?: string;
    description?: string;
    cancelLabel?: string;
    confirmLabel?: string;
    colorScheme?: string;
  }) {
    setIsOpen(true);
    setValues({
      title,
      description,
      cancelLabel,
      confirmLabel,
      colorScheme,
    });

    return new globalThis.Promise<boolean>((resolve) => {
      resolver.current = resolve;
    });
  }

resolver is a ref inside my component that i call on confirm or cancel of the modal.

The problem is that when i try to assign my handleShow inside the provider, like this:

<ConfirmerContext.Provider value={{ show: handleShow }}>
  {children}
</ConfirmerContext.Provider>

I get the following error:

Type 'Promise<boolean>' is missing the following properties from type '{ new (executor: (resolve: (value: boolean | PromiseLike<boolean>) => void, reject: (reason?: any) => void) => void): Promise<boolean>; all<T>(values: Iterable<T | PromiseLike<T>>): Promise<...>; all<T extends readonly unknown[] | []>(values: T): Promise<...>; ... 6 more ...; readonly [Symbol.species]: PromiseConstr...': all, race, prototype, reject, and 4 more.
graceful nymph
#

the latter type seems to represent typeof Promise, it has a constructor and methods like all

#

so you're trying to assign a promise to a promise class

#

your createContext's argument's show parameter is a function value, not a function type. it returns the promise class

#

so there it is

thorn seal
#

Thank you so much for responding to me.. could you please explain a bit more?

#

So should I change the type definition of my context?

graceful nymph
#

your context isn't a type definition

#

it's just a value, an expression

thorn seal
#

Oooooh

#

Damn, right

graceful nymph
#

it has types inside with the options parameter and the boolean used as a generic, but the other parts are values

#

be careful not to confuse : in objects/classes vs annotations/types, and => in functions vs function typings
they're based on context

thorn seal
#

Thanks, i changed my context definition, but now i don't know what the correct initial value should be, since i define my context before my function handleShow.

graceful nymph
#

i've seen null iirc, maybe that? im not familiar with react sorry

thorn seal