在 Typescript 中,我如何允许一个类型拥有指向该类型的递归值的泛型的所有键?

In Typescript how do I allow a type to have all keys of a generic that point to a recursive value of that type?

现在我有这样的东西,其中 "any" 可以充当通用 "V"

interface Validation<V> {
  $isValid: boolean
  $isValidating: boolean
  $value: V
  [prop: string]: boolean | V | Validation<V>
}

我想做的是将字符串索引类型替换为 V 中的任何字符串键 K 将 return 子验证接口。

interface Validation<V> {
  $isValid: boolean
  $isValidating: boolean
  $value: V
  [K extends Extract<keyof V, string>]: Validation<V[K]>
}

这显然行不通,很想知道是否可以实现类似的东西。

是的。方法如下

type Validation<V> = {
    [K in Extract<keyof V, string>]: Validation<V[K]>
} & {
    $isValid: boolean
    $isValidating: boolean
    $value: V
}
  1. 你应该用mapped type,所以你应该写K in ...

    The syntax resembles the syntax for index signatures with a for .. in inside. There are three parts:

    • The type variable K, which gets bound to each property in turn.

    • The string literal union Keys, which contains the names of properties to iterate over.

    • The resulting type of the property.
  2. 要添加其他属性,请使用 intersection,因为无法直接向映射类型添加其他属性。