Typescript 当递归时,映射记录导致任何类型

Typescript 当递归时,映射记录导致任何类型,typescript,Typescript,我使用映射类型来转换数据结构,除了存在递归字段外,数据结构的工作方式与预期一致 有没有办法防止它变成任何类型 type DataType<T extends Record<keyof T, Obj<any, any>>> = { [P in keyof T]: T[P]['data'] } // I need to be able to pass in a Data generic // to this object class Obj< Da

我使用映射类型来转换数据结构,除了存在递归字段外,数据结构的工作方式与预期一致

有没有办法防止它变成任何类型

type DataType<T extends Record<keyof T, Obj<any, any>>> = {
  [P in keyof T]: T[P]['data']
}

// I need to be able to pass in a Data generic
// to this object
class Obj<
  Data extends DataType<T>,
  T extends Record<keyof Data, Obj<any, any>>
> {
  constructor(public fields: T) {}

  public data: Data
}

const recursive = new Obj({
  // With this field, the 'recursive' variable becomes type 'any'
  get query() {
    return recursive
  },
  test: new Obj({})
})

// Without recursive field it works as expected
const nonRecursive = new Obj({ test: new Obj({}) })
nonRecursive.data.test // okay
type数据类型={
[P in keyof T]:T[P]['data']
}
//我需要能够传递数据
//为了这个目标
Obj类<
数据扩展数据类型,
T延续记录
> {
构造函数(公共字段:T){}
公共数据:数据
}
const recursive=新对象({
//使用此字段,“递归”变量将变为“any”类型
获取查询(){
返回递归
},
测试:新Obj({})
})
//如果没有递归字段,它将按预期工作
常量非递归=新对象({test:new Obj({})})
非递归的.data.test//OK

嗯,这里有很多相互引用的泛型类型,没有用例和示例,我承认我几乎不知道这里发生了什么,也不知道这是否是表示数据结构的最佳方式。我猜您可能只需要这样一个类型参数:

class Obj<T>
{
    constructor(public fields: { [K in keyof T]: Obj<T[K]> }) {
    }
    public data!: T
}
下面是我如何使用上面列出的简化的
Obj
类型I:

// explicit type
interface RecursiveData {
    readonly query: RecursiveData,
    test: {}
}

const recursive = new Obj({
    // explicitly annotated return type
    get query(): Obj<RecursiveData> {
        return recursive
    },
    test: new Obj({})
}); // okay now
//显式类型
接口递归数据{
只读查询:递归数据,
测试:{}
}
const recursive=新对象({
//显式注释的返回类型
获取查询():Obj{
返回递归
},
测试:新Obj({})
}); // 好了

好的,希望能有帮助。祝你好运

嗯,这里有很多相互引用的泛型类型,没有用例和示例,我承认我几乎不知道这里发生了什么,也不知道这是否是表示数据结构的最佳方式。我猜您可能只需要这样一个类型参数:

class Obj<T>
{
    constructor(public fields: { [K in keyof T]: Obj<T[K]> }) {
    }
    public data!: T
}
下面是我如何使用上面列出的简化的
Obj
类型I:

// explicit type
interface RecursiveData {
    readonly query: RecursiveData,
    test: {}
}

const recursive = new Obj({
    // explicitly annotated return type
    get query(): Obj<RecursiveData> {
        return recursive
    },
    test: new Obj({})
}); // okay now
//显式类型
接口递归数据{
只读查询:递归数据,
测试:{}
}
const recursive=新对象({
//显式注释的返回类型
获取查询():Obj{
返回递归
},
测试:新Obj({})
}); // 好了
好的,希望能有帮助。祝你好运