是否可以在打字稿中没有明确定义的情况下创建嵌套泛型

Is it possible to create nested generics without explicit definition in typescript

我在编写将一种类型应用于另一种类型的所有底层道具的类型时遇到问题。

这样做的目的是使用创建一个类型,它可以将所有底层道具转换为 Vue 3 的 Ref

// Start with some type T
type T = ...

// And a 'function' to apply, U
type U<T> = ...

// This needs to apply U to all bottom level properties of T
// ('bottom level' are all props who's type does not extend object)
type DeepApply<T,U> = ???

示例:

{
  a: string,
  b: number,
  c: {
    c1: number,
    c2: string
  }
}

会变成

{
  a: Ref<string>,
  b: Ref<number>,
  c: {
    c1: Ref<number>,
    c2: Ref<string>
  }
}

这是我最好的镜头,但 TS 在尝试为泛型提供它自己的泛型参数 (U) 时以及在尝试将具有泛型的类型作为泛型传递而不显式定义它时都会抛出错误泛型 (DeepApply).

type DeepApply<T, U> = {
  [P in keyof T]: T[P] extends object ? DeepUnion<T[P], U> : U<T[P]>;
};

type MyRefType = DeepApply<MyType, Ref>

当引用一个类型时,它的所有泛型参数必须满足。换句话说,您不能传递没有参数的参数化类型,以便稍后填充它的参数。只是没有语法。

但是,如果您对 Ref 类型进行硬编码,则可以做到这一点。例如:

type DeepApplyRef<T> = {
  [P in keyof T]: T[P] extends object ? DeepApplyRef<T[P]> : Ref<T[P]>;
};

我认为不存在像您在这里想要的那样动态的解决方案,如果您的递归类型知道它用来包装事物的类型,那么它确实可以正常工作。

Playground