// Provided input
const input: Input = {
  hello: {
    type: "string",
  },
  first: {
    second: {
      type: "number"
    }
  }
}

// Expected output
const output = {
  hello: "some-string",
  first: {
    second: 42
  }
}

// Function that processes the input and spits out the expected output
function processInput<T extends Input>(input: T): Output<T> {
  // Some logic
}

我想使用processInput函数处理嵌套的input对象,以生成类似output对象的输出.这可以通过判断type属性是否存在等简单地完成.

但我的"问题"是Output型.我想根据提供的输入准确地输入输出.

这就是我到目前为止想出来的:

export type Property = { type: "string" } | { type: "number" };
export type Input = { [key: string]: Property | Input };

export type Output<T extends Input> = {
  [Key in keyof T]:
    T[Key] extends { type: "string" } ? string :
    T[Key] extends { type: "number" } ? number :
    T[Key] extends Input ? Output<T[Key]> :
    never
};

但在访问hello属性(如output.hello)时,它始终是类型never

推荐答案

如果输入是动态的,这是不可能的.

TypeScrip只在编译时运行,因此它无法推断动态对象具有哪些属性,因为这些信息还不存在.

如果对象是静态的(在实际有用的代码中不太可能),您可以使用乌克兰的解决方案中的队长-约塞里安:

export type Property = { type: "string" } | { type: "number" };
export type Input = { [key: string]: Property | Input };

export type Output<T extends Input> = {
  [Key in keyof T]:
  T[Key] extends { type: "string" } ? string :
  T[Key] extends { type: "number" } ? number :
  T[Key] extends Input ? Output<T[Key]> :
  never
};

function processInput<T extends Input>(input: T): Output<T>
function processInput<T extends Input>(input: T) {
  return null as any
}

const result = processInput({
  hello: {
    type: "string",
  },
  first: {
    second: {
      type: "number"
    }
  }
})

Typescript相关问答推荐

类型脚本泛型最初推断然后设置

如何正确地对类型脚本泛型进行限制

我可以为情态车使用棱角形的路由守卫吗?

在包含泛型的类型脚本中引用递归类型A<;-&B

如何将别名添加到vitest配置文件?

防止重复使用 Select 器重新渲染

NPM使用Vite Reaction应用程序运行预览有效,但我无法将其部署到Netlify

为什么特定的字符串不符合包括该字符串的枚举?

如何从接口中省略接口

TypeScrip:如何缩小具有联合类型属性的对象

设置不允许相同类型的多个参数的线性规则

垫子工具栏不起作用的Angular 布线

如何在Angular /字体中访问API响应的子元素?

使用RXJS获取数据的3种不同REST API

如何处理可能为空的变量...我知道这不是Null?

可以将JS文件放在tsconfig';s includes/files属性?或者,我如何让tsc判断TS项目中的JS文件?

参数未映射泛型返回类型

如何将 MUI 主题对象的自定义属性与情感样式组件中的自定义props 一起使用?

使用本机 Promise 覆盖 WinJS Promise 作为 Chrome 扩展内容脚本?

具有来自其他类型的修改键名称的 TypeScript 通用类型