简体   繁体   English

TS 4.6 上具有推理和扩展子句的条件类型

[英]Conditional type with inference and extends clause on TS 4.6

I wrote the following types with TS 4.7 in mind:我在考虑 TS 4.7 的情况下编写了以下类型:

const routes = {
  foo: '/foo/:paramFoo',
  bar: '/bar/:paramFoo/:paramBar',
  baz: '/baz/baz2/:paramFoo/:paramBar',
} as const;

type Routes = typeof routes;

type RouteParser<S extends string> =
  string extends S ? string[] :
  S extends '' ? [] :
  S extends `${infer T}/:${infer U}` ? [T, ...RouteParser<U>] : [S]; 

type RouteParams<S extends string> = RouteParser<S> extends [infer path, ...infer params extends string[]] ? { // can't do that in TS 4.6 
  [K in params[number]]: string;
} : { [x in string]: string; };


function navigateTo<T extends keyof Routes, U extends Routes[T]>(route: U, params: RouteParams<U>) {
  let actualRoute: string = route;
  Object.keys(params ?? {}).forEach((param) => {
    actualRoute = actualRoute.replace(`:${param}`, param in params ? params[param] : '');
  })

  console.log(actualRoute);
}



navigateTo(routes.foo, { paramFoo: 'foo' })
navigateTo(routes.bar, { paramFoo: 'foo', paramBar: 'bar' })
navigateTo(routes.baz, { paramFoo: 'foo', paramBar: 'bar' })
navigateTo(routes.baz, { paramFoo: 'foo', paramBar: 'bar' })

I am currently stuck on an Angular 13 project though, and I can't use the extends clause feature brought by TS 4.7我目前被困在 Angular 13 项目上,但我无法使用 TS 4.7 带来的extends子句功能

How could I rewrite it to work with TS 4.6?我如何重写它以使用 TS 4.6?

Playground (using version 4.6) 游乐场(使用 4.6 版)

In 4.6, we would write the following:在 4.6 中,我们将编写以下内容:

type RouteParams<S extends string> = RouteParser<S> extends [infer path, ...infer params] ? params extends string[] ? {
  [K in params[number]]: string;
} : { [x in string]: string; } : { [x in string]: string; };

Which is why we have the new extends in infer clauses in 4.7.这就是为什么我们在 4.7 的 infer 子句中有新的扩展。

You have to move the params extends string[] into its own conditional.您必须将params extends string[]移动到它自己的条件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM