简体   繁体   English

是否可以在 typescript 中没有明确定义的情况下创建嵌套的 generics

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

I am having trouble writing a type that applies one type to all the bottom level props of another type.我无法编写将一种类型应用于另一种类型的所有底层道具的类型。

The purpose of this is to use create a type which can convert all bottom level props to Ref<T> for Vue 3.这样做的目的是为 Vue 3 创建一个可以将所有底层道具转换为 Ref<T> 的类型。

// 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> = ???

Example:例子:

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

Would become会成为

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

Here's my best shot but TS throws an error both when trying to give a generic its own generic arguments (U<T[P]>) and when trying to pass a type with generics as a generic without explicitly defining its generics (DeepApply<T, Ref>).这是我最好的方法,但是 TS 在尝试为泛型提供自己的泛型 arguments (U<T[P]>) 以及尝试将带有 generics 的类型作为泛型传递而不明确定义其 Z56B97998B338B9370ZA 时都会引发错误。 , 参考>)。

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

type MyRefType = DeepApply<MyType, Ref>

When a type is referenced, all it's generic parameters must be satisfied.引用类型时,必须满足其所有泛型参数。 Put another way, you can't pass a parameterized type without parameters to have it's parameters filled in later.换句话说,你不能传递一个没有参数的参数化类型,以便稍后填写它的参数。 There's just no syntax for that.只是没有语法。

However, you can do it if you hardcode the Ref type.但是,如果您对Ref类型进行硬编码,则可以这样做。 For example:例如:

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

I don't think a solution exists that is quite as dynamic as you want here, if your recursive type knows the type that it's wrapping things up with, then this does work just fine.我认为这里不存在像您想要的那样动态的解决方案,如果您的递归类型知道它正在包装的类型,那么这确实可以正常工作。

Playground 操场

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

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