打字稿:自动完成不起作用,减少和可选承诺的组合

Typescript: autocompletion isn't working, composition with reduce & optional promises

我第一次尝试使用打字稿进行合成,我查找了解决方案但找不到适合我问题的方法。

一般来说,在 TypeScript 中,如果我们有这样的东西:

import * as fs from 'fs';
import { resolve } from 'path';

const open = (path: string, flags: T_FS_TYPES = "r") => fs.promises.open(path, flags);

const isExist = (path: string) => fs.existsSync(path);

const resolvePath = (path: string) =>
  path.startsWith("/") ? path : resolve(path);

open(isExistHandled(resolvePath("data")))
  .then((data) => {
    data // data will autocomplete just fine
  });

我尝试用 reduce 构建一个 composer,但它没有自动完成,直到我不知道我在做什么:

const compose:
<T extends any | Promise<any>>(...funcs: Function[]) => (value: T) => any | Promise<any>
=
<T extends any | Promise<any>>(...funcs: Function[]) => (value) =>
  funcs.reduce<T>((v, f) => f(v), <T>value);

compose(
  resolvePath,
  isExistHandled,
  open
)("data")
  .then((data) => {
    data // I got to the point where everything is fine but it's not autocompleting here.
  });

所以简而言之,我期待一个函数被调用并获取其前一个的最后结果,return它到链上的下一个,自动完成工作就像第一个代码片段。

我在空闲时间做了一些研究来解决这个问题,我最终找到了这篇文章,其中我可以 select 数组中的最后一个元素,所以我考虑提供 ...funcs 作为元组代替。

type LengthOfTuple<T extends any[]> = T extends { length: infer L } ? L : never;

type DropFirstInTuple<T extends any[]> = ((...args: T) => any) extends (arg: any, ...rest: infer U) => any ? U : T;

type LastInTuple<T extends any[]> = T[LengthOfTuple<DropFirstInTuple<T>>];

type Composer =
  <T extends any[]>(...funcs: T) => 
  (value: any) => ReturnType<LastInTuple<T>>;

const composer: Composer = (...funcs) => {
  return (value) => funcs.reduce((v, f) => f(v), value)
}

还是太长了,希望有朝一日有人能看到这篇文章并提供更好的答案,欢迎更新答案...

旁注:这只是一个副项目,但我仍然有兴趣了解更多信息,并保留它作为参考。

文章参考:https://dev.to/miracleblue/how-2-typescript-get-the-last-item-type-from-a-tuple-of-types-3fh3