使用typescript输入自定义URLBuilder

mu0hgdu0  于 2023-08-08  发布在  TypeScript
关注(0)|答案(1)|浏览(129)

我一直在尝试创建一个自定义(使用typescript输入)URLBuilder(使用builder设计模式)功能,我希望将其设计为尽可能可重用,现在我被URL的第一部分卡住了,这是路径
查询部分稍微简单一些,我设法做到了,但是path部分比我预期的要难。

那么这个想法是什么:

1.第一种方式是直接将端点传递给构造函数:

type Path = {
  path1: "fixtures" | "teams";
  path2: { fixtures: "statistics" | "lineups"; teams: "seasons" | "countries" };
};

class URLMultiplePaths<P extends Path> {
  constructor(path1: P["path1"], path2: P["path2"][P["path1"]]) {}

  setPath(path: P) {
    return this;
  }
}

const url = new URLMultiplePaths("fixtures", "");

字符串
我希望每个下一个路径的类型都依赖于前一个路径,并且当传递参数时在引号内按ctr + space时,只获得依赖于前一个路径的选项。
因此,如果我将path 1设置为fixtures,则下一个path的选项应为statisticslineups,如果我将path 1设置为teams,则path 2的选项应为seasonscountries
这个-path2: P["path2"][P["path1"]]在理论上应该可以工作,但是typescript不能从代码的谎言中推断出类型。
请记住,这个构建器的目标是使用不同数量的参数…

2.第二种方法是将端点传递给setPath方法:这样我就可以一条一条地链接路径。但是我不知道下一个路径是如何根据前一个输入的。所以这就是为什么我试图实现上面的例子,然后我可以考虑用方法和链接实现它路径

  • 但如果你有关于第二个的想法,请分享,我认为它会更好一点,也许更干净。
pbossiut

pbossiut1#

我想你可以用conditional types做到这一点:

type FixturePath = "fixtures";
type TeamsPath = "teams";
type OtherPath = "other";

type GenericPath<T extends FixturePath | TeamsPath | OtherPath> = {
    path1: T;
    path2: T extends FixturePath ? "statistics" | "lineups" :
        T extends TeamsPath ? "seasons" | "countries" :
            T extends OtherPath ? "foo" | "bar" : any;
};

// if you don't want the generic type parameter:
type Path = GenericPath<FixturePath> | GenericPath<TeamsPath> | GenericPath<OtherPath>;

const url1: GenericPath<TeamsPath> = {path1: "teams", path2: "seasons"}
const url2: Path = {path1: "teams", path2: "seasons"}

字符串

相关问题