Ответы пользователя по тегу TypeScript
  • Как задать тип функции принимающей промисы и возвращающей выполненые промисы?

    daniel_pr
    @daniel_pr
    Добавьте [].

    T extends Promise<any>[] | []

    Лучше передавать импорты через callback, чтобы они каждый раз не импортировались. Вот моя версия:

    import { DependencyList, useEffect, useRef } from "react";
    
    type Import = Promise<any>;
    
    type AwaitedImports<T extends Import[]> = { [P in keyof T]: Awaited<T[P]> };
    
    type Resolve<T extends Import[]> = (result: AwaitedImports<T>) => void;
    
    function useEffectWithImports<T extends Import[] | []>(
      resolve: Resolve<T>,
      imports: () => T,
      deps?: DependencyList
    ) {
      const resolveRef = useRef(resolve);
      const importsRef = useRef(imports);
      resolveRef.current = resolve;
      importsRef.current = imports;
    
      useEffect(() => {
        const promises = importsRef.current();
        Promise.all(promises)
          .then(resolveRef.current as Resolve<T>)
          .catch(console.error);
      }, deps);
    }
    
    useEffectWithImports(
      ([fs, path]) => {},
      () => [import("fs"), import("path")],
      []
    );
    Ответ написан
    1 комментарий